I have a module that provides some convenience functions for DOM manipulation that I'm trying to test with Jest and jsdom, but I seem to be doing something wrong in instantiating it.
The expect test within dom.window.document.addeventlistener ('domcontentloaded'... is not passing, the console.log I added inside ../mocks/forTesting.js also does not appear when running the test.
Does anyone have any idea how to make this test work? I need the script to run and the div with id="container" change to 'test'
Here is the test code.
import { runScript } from '../export/script.js';
import { JSDOM } from 'jsdom'
const dom = new JSDOM(`<!DOCTYPE html><html><body><div id="container">Hello</div></body></html>`, { resources: 'usable', runScripts: "dangerously" })
global.window = dom.window
global.document = dom.window.document
describe("Rendering Module", () => {
test("Verify if mocked script was executed", async () => {
const script = { name: 'testScript', value: `<script src="../mocks/forTesting.js" ></script>` }
const scriptFreezed = Object.freeze(script);
await runScript(scriptFreezed, dom.window.document);
dom.window.document.addEventListener('DOMContentLoaded', () => {
const text = dom.window.document.getElementById('container').innerHTML;
expect(text).toEqual('test')
});
dom.window.document.dispatchEvent(new dom.window.Event('DOMContentLoaded', {"bubbles": true}))
})
})
The test is giving success as it was passing but is giving this error when running
console.error
Error: Uncaught [Error: expect(received).toEqual(expected) // deep equality
Expected: "test"
Received: "Hello"
Here is the code in ../mocks/forTesting.js.
window.document.addEventListener("DOMContentLoaded", function (event) {
console.log('forTesting.js')
window.document.getElementById('container').innerHTML = 'test';
});
Here is the runScript code.
const runScript = (script, dom) => {
const node = dom.createRange().createContextualFragment(script.value);
dom.head.appendChild(node);
}