Mocking `document` in jest

Similar to what others have said, but instead of trying to mock the DOM yourself, just use JSDOM:

// __mocks__/client.js

import { JSDOM } from "jsdom"
const dom = new JSDOM()
global.document = dom.window.document
global.window = dom.window

Then in your jest config:

    "setupFiles": [
      "./__mocks__/client.js"
    ],

I have resolved this using setUpFiles property in jest. This will execute after jsdom and before each test which is perfect for me.

Set setupFiles, in Jest config, e.g.:

"setupFiles": ["<rootDir>/browserMock.js"]


// browserMock.js
Object.defineProperty(document, 'currentScript', {
  value: document.createElement('script'),
});

Ideal situation would be loading webcomponents.js to polyfill the jsdom.


I have been struggling with mocking document for a project I am on. I am calling document.querySelector() inside a React component and need to make sure it is working right. Ultimately this is what worked for me:

it('should test something', () => {
  const spyFunc = jest.fn();
  Object.defineProperty(global.document, 'querySelector', { value: spyFunc });
  <run some test>
  expect(spyFunc).toHaveBeenCalled()
});