为什么 jest/enzyme 不呈现我的 Web 组件?
Why won't jest/enzyme render my Web Component?
我正在使用 jest 26 和 jsdom 16,所以理论上我需要用 web 组件进行单元测试的一切。
我面临的问题是,当我直接使用 document.createElement
实例化 Web 组件时,我可以让 Web 组件工作,但不能通过酶的 mount()
,我需要它来封装测试用例React 组件内的 Web 组件。
我已经知道解决方法(在 React 测试中模拟 Web 组件等),但是 1. 这比我想要的端到端要少 2. 我不想模拟所有网络组件。
到目前为止,我找不到 patches/workarounds 酶方法。有什么想法吗?
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
});
});
如果您尝试呈现 Web 组件,我的经验是您需要 运行 在支持 Web 组件的最新环境中开玩笑。你不需要用这个填充多边形。另外,请确保您全面了解最新信息。
"test": "jest --env=jest-environment-jsdom-sixteen"
如果您使用 testing-library,您需要做的第二件事是让 Web 组件在
中获得渲染周期
const {container} = render(<WebComponent/>)
await waitFor(() => {
expect(container.querySelector("input")).toBeTruthy()
})
您的查询选择器正在寻找您的 Web 组件内部的内容,这些内容在完成呈现周期后才会出现。
一旦通过,您的其余断言和测试将可以正确访问底层 dom。
我正在使用 jest 26 和 jsdom 16,所以理论上我需要用 web 组件进行单元测试的一切。
我面临的问题是,当我直接使用 document.createElement
实例化 Web 组件时,我可以让 Web 组件工作,但不能通过酶的 mount()
,我需要它来封装测试用例React 组件内的 Web 组件。
我已经知道解决方法(在 React 测试中模拟 Web 组件等),但是 1. 这比我想要的端到端要少 2. 我不想模拟所有网络组件。
到目前为止,我找不到 patches/workarounds 酶方法。有什么想法吗?
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
});
});
如果您尝试呈现 Web 组件,我的经验是您需要 运行 在支持 Web 组件的最新环境中开玩笑。你不需要用这个填充多边形。另外,请确保您全面了解最新信息。
"test": "jest --env=jest-environment-jsdom-sixteen"
如果您使用 testing-library,您需要做的第二件事是让 Web 组件在
中获得渲染周期 const {container} = render(<WebComponent/>)
await waitFor(() => {
expect(container.querySelector("input")).toBeTruthy()
})
您的查询选择器正在寻找您的 Web 组件内部的内容,这些内容在完成呈现周期后才会出现。
一旦通过,您的其余断言和测试将可以正确访问底层 dom。