I have a product code that injects javascript into document head. I want to write unit test for it. The problem is that jest fails with timeout error. I understand it’s the resolve method of Promise that needs to be called, but I am unable to figure out how will I do it with jest. I tried to create document from JSDOM, but in that approach as well, the promise will not be resolved.
snippet from product code
export async function injectScript() {
await new Promise((resolve, reject) => {
const element = document.createElement("script");
element.setAttribute("type", "text/javascript");
element.setAttribute("src", `/mycode.js`);
document.getElementsByTagName("head")[0]?.appendChild(element); // head should not be null
element.onload = resolve;
element.onerror = reject;
});
return "test";
}
my test code
import { injectScript } from "../MyUtil";
describe("MyFunction", () => {
it("should return the expected result", async () => {
const result = await injectScript();
expect(result).toBe("test");
});
});
I get error thrown: “Exceeded timeout of 5000 ms for a test. But this will not be solved by increasing timeout.
How will I mock or use JSDOM or other mechanism so that onload is called after document is injected and the promise resolves in my test code?