【问题标题】:Why won't jest/enzyme render my Web Component?为什么 jest/enzyme 不会渲染我的 Web 组件?
【发布时间】:2020-10-20 23:37:18
【问题描述】:

我将 jest 26 与 jsdom 16 一起使用,因此理论上我使用 Web 组件进行单元测试所需的一切。

我面临的问题是,当我直接使用 document.createElement 实例化 Web 组件时,我可以让它们工作,但不能通过酶的 mount(),我需要将 Web 组件封装在 React 中的测试用例组件。

我已经知道一些变通方法(在 React 测试中模拟 Web 组件等),但是 1. 这比我想要的要少,而且 2. 我不想模拟所有 Web 组件.

到目前为止,我找不到酶法的补丁/解决方法。有什么想法吗?

describe("Web Component Test", () => {

  // Define a small custom Web Component

  class Test extends HTMLElement {
    connectedCallback() {
      this.myChild = document.createElement("div");
      this.myChild.className = "the_child";
      this.appendChild(this.myChild);
    }

  }

  customElements.define("x-test", Test);

  // Try instantiating it with document.createElement() - THIS WORKS

  test("createElement x-test", () => {
    const c = document.createElement("x-test");
    document.body.appendChild(c);
    expect(c.childNodes).toHaveLength(1);
  });

  // Try instantiating it with enzyme/mount() - THIS FAILS

  test("mount x-test", () => {
    const c = mount(<x-test />).getDOMNode();
    expect(c.childNodes).toHaveLength(1); // <-- 0 because connectedCallback() not called
  });
});

【问题讨论】:

标签: jestjs enzyme web-component


【解决方案1】:

如果您尝试渲染 Web 组件,我的经验是您需要在支持 Web 组件的最新环境中运行 jest。你不需要用这个填充多边形。另外,请确保您全面了解最新信息。

    "test": "jest --env=jest-environment-jsdom-sixteen"

如果您使用测试库,您需要做的第二件事是让 Web 组件在其中获得一个渲染周期

    const {container} = render(<WebComponent/>)
    await waitFor(() => {
      expect(container.querySelector("input")).toBeTruthy()
    })

您的查询选择器正在寻找您的 Web 组件的内部内容,这些内容在完成渲染周期后才会出现。

一旦通过,其余的断言和测试将可以正确访问底层 dom。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 2018-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-20
    • 2020-05-06
    • 2020-10-15
    相关资源
    最近更新 更多