【问题标题】:how to unit test polyfilled webcomponents custom element如何对 polyfill webcomponents 自定义元素进行单元测试
【发布时间】:2017-04-25 08:33:09
【问题描述】:

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

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

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

【问题讨论】:

  • 您有没有找到解决方案,或者您有如何做到这一点的示例?我在同样的情况下苦苦挣扎......
  • 不,没有解决方案...

标签: javascript unit-testing jasmine web-component custom-element


【解决方案1】:

您是否尝试在 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

【讨论】:

    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 2011-10-02
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    相关资源
    最近更新 更多