'How to test Custom Elements / Web Components with Testing-Library, Jest and JSDOM?

I am trying to test an Angular app with testing-library/angular@11 and [email protected] which uses custom-elements quite heavily.

Unfortunately I am not quite sure if testing-library/JSDOM/Jest just don't support the rendering of custom-elements or if I am missing something. The stylelib we're using is build with stencil, shadow-dom is not used.

Example template with custom-element:

<div>
  <my-custom-element title="some-title"></my-custom-element>
</div>

Rendered custom-element template example (which in this case just renders a button with the provided title-prop)

<my-custom-element title="some-title">
  <button>some-title</button>
</my-custom-element>

If I run testing-library's render()-function and print the screen, the custom-element-tag is rendered, but its child components are not:

<head>
  ...
</head>
<body>
  ...
  <div>
    <my-custom-element title="some-title"></my-custom-element>
  </div>
</body>

So if I were to run expect(screen.getByRole("button")).toBeTruthy() the test would fail.

There's an open pull request for shadow-dom support: https://github.com/testing-library/dom-testing-library/pull/1069 and https://dev.to/ionic/testing-web-components-in-react-4e49 hints that it's currently not possible to test CEs...

Am I missing something or am I just wasting time atm? I would argue in this case that it's also not testing of implementation details as in most cases I just want to check if a text is rendered to the screen or not.



Solution 1:[1]

Your web component is not defined thats why the tag is just rendered, not its contents. You should bundle and load all your web components in your test setup (wrapper around all tests).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Chrissi Grilus