I want to test the content of a slot in one of my custom components. If I use my component in an html-file and open it in an browser, everything works as intended. However if I want to automate my test with jest, it fails. Below is an minimal working example with the output form 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");
});
});
output:
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)