3

I am trying to test an Angular app with testing-library/angular@11 and jest@27.4.4 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.

felix
  • 61
  • 6

2 Answers2

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).

Chrissi Grilus
  • 1,099
  • 2
  • 9
  • 21
0

@Chrissi Grilus is right, I had a similar problem and ended up adding that custom component into the declarations, after that it displayed the child components for that component.

e.g. :

await render(ParentComponent, {
imports : [],
providers: [],
declarations: [MyCustomChildComponent] // here is where you add that component
})
Zaid Shawahin
  • 355
  • 2
  • 18
  • 1
    First of all, thanks for the answer. The element is actually not an angular component but a web-component, so that's unfortunately not going to work since it's not known to the angular compiler – felix Jun 16 '22 at 07:57
  • 1
    maybe test this in cypress instead as an integration/e2e test? – Zaid Shawahin Jun 16 '22 at 13:32
  • 1
    yep, this will probably be the way to go as testing-library/JSDOM is currently not supporting custom-elements – felix Jun 16 '22 at 13:39