小编Nil*_*ils的帖子

动态实例化 Web 组件的方法之间的差异

Web 组件(仅针对此问题的自主自定义元素)可以通过多种方式“实现”。

以下三个选项之间是否存在显着差异?

选项1:

const foo = document.createElement('foo-element');
document.body.appendChild(foo);
Run Code Online (Sandbox Code Playgroud)

选项 2:

const div = document.createElement('div');
div.innerHTML = '<foo-element></foo-element>'
const foo = div.firstElementChild;
document.body.appendChild(foo);
Run Code Online (Sandbox Code Playgroud)

选项 3:

const foo = new FooElement;
document.body.appendChild(foo);
Run Code Online (Sandbox Code Playgroud)

我基于 Karma/Mocha 堆栈编写了一些单元测试,并使用选项 3 创建了我的实例。

这是否足够,也就是说,我可以使用任一方法依赖具有相同状态/行为的组件,还是有必要使用所有不同的实例化选项重复我的所有测试?

document.createElement由于错误,我的 Web 组件之一无法使用实例化:

VM977:1 Uncaught DOMException: Failed to construct 'CustomElement':
The result must not have attributes
at <anonymous>:1:10
Run Code Online (Sandbox Code Playgroud)

可以毫无问题地实例化相同的组件这一事实new告诉我,在幕后,必须存在显着差异,尤其是new FooElement和之间document.createElement('foo-element')

我可以编写三个通用测试来测试所有三种实例化方式,当然,但这足够了吗?

或者我所有现有的测试都应该使用所有 3 个实例化选项运行?

或者换个方式问:

实例化后每个实例是否完全相同?(假设没有错误)

javascript web-component custom-element native-web-component

6
推荐指数
1
解决办法
301
查看次数