Mocking global.window for fun

I have a function that works on both node and browser, which I want to test with a joke:

const myFn = () => { if(typeof window !== 'object'){ return 1; } return 2; } 

How can I set the global window object to undefined in order to check the node branch and return this value.

eg.

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

Ive tried the suggestions here without success: Mocking Globals at Jest

+5
source share
1 answer

You can try using @jest-environment docblock, available since v20.0.0, to change the environment for different tests. The default is 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(); }); 

Link: https://facebook.imtqy.com/jest/docs/en/configuration.html#testenvironment-string

+4
source

Source: https://habr.com/ru/post/1275241/


All Articles