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.
From reading other questions and answers (such as this one) I understand that Jest's testing environment is automatically set to use jsdom and that you need to replace global.document, but it's not working as I currently have it.
Here's the smallest test case to reproduce the problem:
// domUtils.js function el(id) { return document.getElementById(id); } and
// domUtils.test.js import { JSDOM } from "jsdom"; import * as domUtils from "../src/domUtils"; describe("DOM operations", () => { // Workaround for jsdom issue 2304 - needed for later localStorage tests const url = "http://localhost"; const documentHTML = '<!DOCTYPE html><div id="lorem" class="test">Lorem ipsum</div>'; global.document = new JSDOM(documentHTML, { url }); test("Get an element from the DOM", () => { const loremDiv = domUtils.el("lorem"); expect(loremDiv.constructor.name).toEqual("HTMLDivElement"); }); } This results in TypeError: Cannot read property 'constructor' of null. Replacing the call to domUtils.el() with document.getElementById() results in the same error.
Is it a loading order problem of some sort, or something else?