Search code examples
testinglit

How to access shadowDom when testing Lit element with open-wc


Lit docs refer to Web Test Runner as testing. It navigates to this example page.

I tried testing MyElement, which has only one <p>.

import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";

@customElement("my-element")
export class MyElement extends LitElement {
  render() {
    return html`<p>Hello, World.</p>`;
  }
}

declare global {
  interface HTMLElementTagNameMap {
    "my-element": MyElement;
  }
}

When testing by open-wc, the element's shadowDom did not have <p> in descendant.

import { expect, fixture, html } from "@open-wc/testing";
import { MyElement } from "../src/MyElement";

it("get shadowDom", async () => {
  const el: MyElement = await fixture(html`<my-element></my-element>`);
  expect(el).shadowDom.to.be.not.null; // passed
  expect(el).shadowDom.to.have.descendant("p"); // failed
});

Does it need more setup to test Lit elements with open-wc? web-test-runner.config.js is:

import { esbuildPlugin } from '@web/dev-server-esbuild';

export default {
  files: ['test/*.test.ts'],
  plugins: [esbuildPlugin({ ts: true })],
};

Solution

  • Try shadowRoot instead of shadowDom:

    it("get shadowDom", async () => {
        const el = await fixture(
          html` <my-element></my-element>`
        );
        const descendant = el.shadowRoot!.querySelector("p")!;
        expect(descendant).to.be.not.null;
    });