首页 文章

如何对polyfilled webcomponents自定义元素进行单元测试

提问于
浏览
1

我想对使用 webcomponents.js polyfill的web组件进行单元测试 .

我的组件是用es6 scss制作的,并且使用构建任务,我将es6转换为es5,将scss处理为css并将两个结果文件插入到html文件中,以便在我的应用程序中使用 HTML Import functionnality的组件 . 以下是自定义元素声明的组件类的示例:

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 ...

1 回答

相关问题