I would like to test some custom web components and use jest.js as test runner (due to its support for ES6).
Chromium supports commands like
window.customElements.define('my-custom-element', MyCustomElementClass);
to register a custom web component.
However, window.customElements
does not seem to be known in the context of jest tests.
As a work around I tried to use jest in combination with puppeteer and express to run the customElements
part in Chromium.
However, I have difficulties to inject the custom element class TreezElement
in the evaluated code:
treezElement.js:
class TreezElement extends HTMLElement {
connectedCallback () {
this.innerHTML = 'Hello, World!';
}
}
treezElement.test.js:
import TreezElement from '../../src/components/treezElement.js';
import puppeteer from 'puppeteer';
import express from 'express';
describe('Construction', ()=>{
let port = 3000;
let browser;
let page;
let element;
const width = 800;
const height = 800;
beforeAll(async () => {
const app = await express()
.use((req, res) => {
res.send(
`<!DOCTYPE html>
<html>
<body>
<div id="root"></div>
</body>
</html>`
)
})
.listen(port);
browser = await puppeteer.launch({
headless: false,
slowMo: 80,
args: [`--window-size=${width},${height}`]
});
var pages = await browser.pages();
page = pages[0];
await page.setViewport({ width, height });
await page.goto('http://localhost:3000');
element = await page.evaluate(({TreezElement}) => {
console.log('TreezElement:')
console.log(TreezElement);
window.customElements.define('treez-element', TreezElement);
var element = document.create('treez-element');
document.body.appendChild(element);
return element;
}, {TreezElement});
});
it('TreezElement', ()=>{
});
afterAll(() => {
browser.close();
});
});
Maybe TreezElement
is not serializable and therefore undefined
is passed to the function.
If I try to import the custom element class TreezElement
directly from within the evaluated code ...
element = await page.evaluate(() => {
import TreezElement from '../../src/components/treezElement.js';
console.log('TreezElement:')
console.log(TreezElement);
window.customElements.define('treez-element', TreezElement);
var element = document.create('treez-element');
document.body.appendChild(element);
return element;
});
... I get the error
'import' and 'export' may only appear at the top level
=> What is the recommended way to test custom web components with jest?
Some related stuff:
See Question&Answers more detail:
os