使用 open-wc 测试 Lit 元素时如何访问 shadowDom

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.

我试过测试 MyElement,它只有一个 <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;
  }
}

用open-wc测试时,元素的shadowDomdescendant中没有<p>

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
});

是否需要更多设置才能使用 open-wc 测试 Lit 元素? 网络测试-runner.config.js 是:

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

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

尝试使用 shadowRoot 而不是 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;
});

我有类似的问题。在我的例子中,shadowRoot 是“null”。要获得 shadowRoot 内容,我必须像这样导入我的 Web 组件:

import './myWebcomponent';