'How to pass document variable to ES6 Module during Jasmine testing

I want to test if a function in a module generated something in document but I am having trouble defining the document variable. I have simulated it jsdom but I am unable to define it in module.

In my actual project, I use the document, window and MathJax library globally and I don't want to pass it to classes through the constructor unless there is no other way.

Example of a class I want to test:

// example.mjs

export class Example {
    createElement() {
        document.createElement("div")
    }
}

Test file:

import {Example} from './example.mjs';
import {JSDOM} from "jsdom";


describe("Example", function () {
    it('should create div', function () {
        const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
        document = dom.window.document; //is it possible to make this defined in all modules

        new Example().createElement() // document is not defined

    });
})

My question is, is it possible to somehow make the document variable defined, so that it can be referenced in the Example class or do I have to pass it in the constructor?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source