我想对使用 webcomponents.js
polyfill 的 Web 组件进行单元测试。
我的组件是用 es6 + scss 制作的,通过构建任务,我将 es6 转换为 es5,将 scss 处理为 css,并将两个结果文件插入 html 文件中,以便在我的应用程序中使用具有 HTML Import
功能的组件。
以下是自定义元素声明的组件类示例:
class my-component extends HTMLElement {
createdCallback() {...}
... //other component methods
//getter/setter
get colors() {
return this._color;
}
set colors(val) {
this._color = val;
}
}
此时我做了一个测试任务,可以启动 Karma
服务器,用 babel
转译 UT 并用 Jasmine
运行 UT。
我的所有测试都在 Chrome 中通过,但在 IE11 中,所有访问 getter/setter 或方法的测试都失败...
示例:
describe...
beforeEach(function() {
this.component = document.createElement(COMP_NAME);
}
it("should return an array", function() {
expect(this.component.colors).toEqual(jasmine.any(Array));
});
});
此 UT 在 Chrome 中会通过,但在 IE 中会失败,错误代码为 Expected undefined to equal <jasmine.any(Array)>
我的诊断是,polyfill 需要一些时间来创建组件。在我的测试中,我将在完全创建组件之前访问组件的 getter(这就是为什么我未定义......) 我尝试推迟测试
setTimeout(() => {
expect(this.component.colors).to...
});
但这有时有效,有时无效......
有人可以告诉我如何解决这个问题吗? 附带说明一下,并非所有组件都会发生这种情况。似乎只适用于具有许多方法/访问器和一些逻辑来运行 onCreate 的方法...
最佳答案
您是否尝试在 beforeEach 函数中使用“whenDefined”?
beforeEach(function(done) {
this.component = document.createElement(COMP_NAME);
customElements.whenDefined(COMP_NAME).then(done)
}
然后测试将在组件升级后运行。
在不使用polyfill的浏览器(如chrome)中,它会立即升级。
参见https://developers.google.com/web/fundamentals/web-components/customelements#api_reference
关于javascript - 如何对 Polyfilled WebComponents 自定义元素进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43605503/