Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 2;
}

How am I able to set the global window object to undefined, to test the node branch, and that 1 is returned.

e.g.

  test('myTest', ()=> {
      global.window = undefined;
      expect(myFn()).toEqual(1); // result: 2
  });

Ive tried the suggestions here with no success: Mocking globals in Jest

like image 383
Daniel Billingham Avatar asked Feb 08 '18 17:02

Daniel Billingham


People also ask

How do you mock global in Jest?

When mocking global object methods in Jest, the optimal way to do so is using the jest. spyOn() method. It takes the object and name of the method you want to mock, and returns a mock function. The resulting mock function can then be chained to a mocked implementation or a mocked return value.

How do you mock a window in Jest?

To mock the JavaScript window object using Jest, we can use the jest. spyOn method. let windowSpy; beforeEach(() => { windowSpy = jest. spyOn(window, "window", "get"); }); afterEach(() => { windowSpy.

Does Jest have a window object?

In Jest environment we do not have window object.


2 Answers

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

like image 61
nbkhope Avatar answered Sep 18 '22 17:09

nbkhope


With new version of jsdom you can do the following:

import { JSDOM } from 'jsdom';

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

describe('', () => {
  it ('', () => {
    const { window } = new JSDOM();
    windowSpy.mockImplementation(() => window);
    // now you have `window` in test environment
  });
});
like image 30
Andrey Edounov Avatar answered Sep 19 '22 17:09

Andrey Edounov