如何测试包含其他模块的自定义元素?

时间:2019-03-26 12:47:35

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

是否有一种方法(使用WCT)测试包括一个外部模块(假设为npm)或另一个自定义元素的自定义元素?

例如,我正在尝试测试如下所示的自定义元素:

// ~/root/src/index.js
import CustomElementChildren from '~/path-to-children';
import NpmModule from 'npm-module';

export default class CustomElement extends HTMLElement {
  constructor() {
    super();

      if(!customElements.get('custom-element-children')){
      customElements.define('custom-element-children', CustomElementChildren);
    }
  }

  // implement some methods that are related with "NpmModule"

  connectedCallback() {
    this.initShadowDom();
  }

  initShadowDom() {
    let shadowRoot = this.attachShadow({mode: 'open'});
    shadowRoot.innerHTML = this.template;
  }

  get template() {
    return `
      <div><custom-element-children></custom-element-children></div>
    `
  }
}
// ~/root/test/index-test.html
<!doctype html>
<html lang="eng">
<head>
    <meta charset="utf8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
    <script src="https://unpkg.com/@webcomponents/shadydom"></script>
    <script src="https://unpkg.com/@webcomponents/custom-elements"></script>
    <script src="../node_modules/web-component-tester/browser.js"></script>
    <script type="module" src="../src/index.js"></script>
</head>
<body>
<custom-element></custom-element>
<script>
  suite('<custom-element>', function() {
    let component = document.querySelector('custom-element');

    test('renders div', () => {
      assert.isOk(component.shadowRoot.querySelector('div'));
    });
  });
</script>
</body>
</html>

发生的问题与语法(导入/导出/等)有关,我找不到为WCT设置webpack / babel的可行方法。

类似的问题here,但不能说与我的问题相同,因为我也希望能够使用绝对导入。

谢谢大家。

0 个答案:

没有答案