Skip to content Skip to sidebar Skip to footer

Mocking Global.window In Jest

I have a function, that runs on both node and in the browser, which I want to test with jest: const myFn = () => { if(typeof window !== 'object'){ return 1; } return

Solution 1:

You can try using the @jest-environment docblock, available since v20.0.0, to change the environment for different tests. By default it uses jsdom, but you can change it to use node. Here is an excerpt from their documentation:

/**
 * @jest-environment jsdom
 */test('use jsdom in this test file', () => {
  const element = document.createElement('div');
  expect(element).not.toBeNull();
});

Ref: https://facebook.github.io/jest/docs/en/configuration.html#testenvironment-string

Solution 2:

With new version of jsdom you can do the following:

import { JSDOM } from'jsdom';

letwindowSpy: any;
beforeEach(() => {
  windowSpy = jest.spyOn(globalasany, 'window', 'get');
});
afterEach(() => {
  windowSpy.mockRestore();
});

describe('', () => {
  it ('', () => {
    const { window } = newJSDOM();
    windowSpy.mockImplementation(() =>window);
    // now you have `window` in test environment
  });
});

Post a Comment for "Mocking Global.window In Jest"