0

I'm trying to test my Lit components with @open-wc/testing. Lit has an example repo here, with this test:

https://github.com/lit/lit-element-starter-ts/blob/main/src/test/my-element_test.ts#L44

When I try to render my element like they do in their example, I get this error:

jtests/components/coding-editor.test.ts:

  Browser logs:
      HTMLElement: <coding-editor></coding-editor>

 ❌ renders
      TypeError: Cannot read properties of null (reading 'querySelector')
        at o.<anonymous> (jtests/components/coding-editor.test.ts:16:30)

My component works in the browser and uses the name "coding-editor". It's as if this test renderer has no idea that I'm using a custom component though. I don't know why shadowRoot is null in my case.

My code is roughly this:

import { CodingEditor } from '../../app/javascript/components/coding-editor';

import {expect, fixture} from '@open-wc/testing';
import {html} from 'lit/static-html.js';


it('renders', async () => {

  const el = await fixture(html`
  <coding-editor></coding-editor>
  `) as CodingEditor;

  console.log(el);
  const text = el.shadowRoot!.querySelector('.table-constrainer');
  // expect(text).to.not.be.null
});

How can I get my test to render this properly, with the shadowRoot populated?

Michael Rivera
  • 193
  • 1
  • 7

1 Answers1

0

This is likely due to TypeScript removing the CodingEditor import that's only used as a type so the side effect of defining the custom element is not happening.

You can either set the TS compiler option importsNotUsedAsValues to preserve (See https://www.typescriptlang.org/tsconfig/#importsNotUsedAsValues) or add another import line for the side-effect like

import '../../app/javascript/components/coding-editor';

Additional explanation here too: https://github.com/Microsoft/TypeScript/wiki/FAQ#why-are-imports-being-elided-in-my-emit

As a side-note, in the starter example you linked to, the imported class is used in assert.instanceOf as a value so it does not get elided by TypeScript.

Augustine Kim
  • 841
  • 1
  • 5