I am using jest 26 with jsdom 16, so theoretically everything that I need for unit tests with web components.
The problem that I am facing is that I can get Web Components to work when I instantiate them directly with document.createElement
, but not through enzyme's mount()
, which I need for test cases which encapsulate a web component inside a React component.
I am already aware of workarounds (mocking the web component in the React tests etc.), but 1. this is less end-to-end than I want it and 2. I don't want to mock all web components.
So far I couldn't find patches/workarounds for the enzyme approach. Any ideas?
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
});
});
If you're trying to render a Web Component, my experience has been that you need to run jest on the latest environment that supports web components. You do not need poly fills with this. Also, make sure you're on latest across the board.
"test": "jest --env=jest-environment-jsdom-sixteen"
If your using testing-library, the second thing you will need to do is let the web component get a render cycle in
const {container} = render(<WebComponent/>)
await waitFor(() => {
expect(container.querySelector("input")).toBeTruthy()
})
Your query selector is looking for something internal to your web component that wont appear until after it's finished its render cycle.
Once that passes, the rest of your assertions and tests will have proper access to the underlying dom.