【发布时间】:2021-11-18 11:23:12
【问题描述】:
我想在我的一个自定义组件中测试插槽的内容。 如果我在 html 文件中使用我的组件并在浏览器中打开它,一切都会按预期工作。但是,如果我想用 jest 自动化我的测试,它会失败。下面是一个输出形式 jest 的最小工作示例:
placeholder.js:
const template = document.createElement("template");
template.innerHTML = `
<p>
<slot></slot>
</p>
`;
class Placeholder extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
get name() {
return this.shadowRoot.querySelector("slot").innerText;
}
}
window.customElements.define("place-holder", Placeholder);
export default Placeholder;
placeholder.test.js:
import Placeholder from "../src/placeholder.js";
describe("name is 'Lorem Ipsum'", () => {
let ph;
beforeAll(() => {
ph = new Placeholder();
const textNode = document.createTextNode("Lorem Ipsum");
ph.appendChild(textNode);
});
test("if the name is 'Lorem Ipsum'", () => {
expect(ph.name).toBe("Lorem Ipsum");
});
});
输出:
name is 'Lorem Ipsum' › if the name is 'Lorem Ipsum'
expect(received).toBe(expected) // Object.is equality
Expected: "Lorem Ipsum"
Received: undefined
11 |
12 | test("if the name is 'Lorem Ipsum'", () => {
> 13 | expect(ph.name).toBe("Lorem Ipsum");
| ^
14 | });
15 | });
at Object.<anonymous> (test/placeholder.test.js:13:25)
at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
at runJest (node_modules/@jest/core/build/runJest.js:387:19)
at _run10000 (node_modules/@jest/core/build/cli/index.js:408:7)
at runCLI (node_modules/@jest/core/build/cli/index.js:261:3)
如您所见,jest 以某种方式无法获取开槽文本并返回undefined。我该如何解决这个问题?
【问题讨论】:
标签: javascript jestjs web-component shadow-dom native-web-component