I want to create lwc component which selectively renders svg from html template files. I wonder how to mock that templates for the needs of JEST test. Import the same templates for component and test is a proper way?
Example:
desert.html
<template>
<svg>...</svg>
<template>
images.js
import { default as desert } from "./desert.html";
export { default as empty } from "./empty.html";
export default {
"no-data:desert": desert
};
illustrationimage.js
import { LightningElement, api } from "lwc";
import { default as images, empty } from "c/images";
export default class IllustrationImage extends LightningElement {
@api imageName;
render() {
if (images[this.imageName]) {
return images[this.imageName];
}
return empty;
}
}
illustrationimage.test.js
import { createElement } from "lwc";
import IllustrationImage from "c/illustrationImage";
describe("c-illustration-image", () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it("Renders image by name", () => {
const element = createElement("c-illustration-image", {
is: IllustrationImage
});
element.imageName = "no-data:desert";
document.body.appendChild(element);
const svg = element.shadowRoot.querySelector("svg");
return Promise.resolve().then(() => {
expect(svg).toBeDefined();
// check that svg is rendered correctly by component
});
});
});
expect
statements about those nodes' properties. If you really want to make sure the rendered SVG is 100% identical to the "desert" SVG, I guess you could have the test import the "desert" SVG directly, and recursively check all the nodes. To me, that would be overkill, but it sort of depends on your testing philosophy.