10
votes

I'm working with jest + enzyme setup for tests. I have function that conditionally renders something if window is defined.

In my test suite I'm trying to reach second case, when window is not defined, but I can't force it.


    it('makes something when window is not defined', () => {
       window = undefined;
       expect(myFunction()).toEqual(thisWhatIWantOnUndefinedWinow);
    });

But even if I force window to be undefined, it doesn't reach expected case, window is always window (jsdom?)

Is it something with my jest setup or I should handle this another way?

2
Your answer possibly will be here stackoverflow.com/questions/41885841/… please let know if you have any concernsXarvalus
It's more about replacing single methods, it's possible for me, but I want to make whole window undefined, I can't do that with that solutionJarosław Wlazło
This one then might be your answer: stackoverflow.com/questions/48691604/…Xarvalus
Yes, that's what I needed, thanks :)Jarosław Wlazło

2 Answers

5
votes

I am able to test the scenario where window is undefined using the below pattern. It allows you to run tests with and without window in the same file. Adding @jest-environment node at the top of the file is not required.

describe('when window is undefined', () => {
    const { window } = global;
    beforeAll(() => {
      // @ts-ignore
      delete global.window;
    });
    afterAll(() => {
      global.window = window;
    });
    
    it('runs without error', () => {
      ...
    });
});

    
3
votes

Here's what I did to force window to be undefined, during selected jest tests.

Test with window = undefined

You can force window to be undefined in some test files by adding @jest-environment node at the top of the file.

test-window-undefined.spec.js

/**
 * @jest-environment node
 */

// ^ Must be at top of file

test('use jsdom in this test file', () => {
  console.log(window)
  // will print 'undefined' as it's in the node environment  
});

Test with window

If you need the window object, simply remove that statement at the top.

credit to this answer here