19

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?

Mark Fraser
  • 3,160
  • 2
  • 29
  • 48
Jarosław Wlazło
  • 370
  • 1
  • 3
  • 14

3 Answers3

18

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', () => {
      ...
    });
});

    
trevorgk
  • 1,436
  • 15
  • 15
5

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

Ben Winding
  • 10,208
  • 4
  • 80
  • 67
  • 1
    This answer doesnt really align to what the question is. In your example you only check if window is defined. Jarosław Wlazło asked how you can mock it to return undefined, as jsdom will make Window available. – Constantin Chirila Sep 16 '20 at 10:32
  • @ConstantinChirila using `@jest-environment node` at the top of the file makes the `window` object undefined... I'll improve the answer a bit more – Ben Winding Sep 18 '20 at 10:08
  • This answer definitely helped me. Used it to get to 100% coverage when writing code meant to run in both node and the browser. – mockaroodev Sep 20 '20 at 08:04
  • In my case couldn't use this approach because I needed the window object to exist in the same test file. – Lianel Feb 14 '23 at 19:41
1

Leave you what it works for me

  const windowDependentFunction = () => {
    if (typeof window === 'undefined') {
      return 'window does not exist'
    }

    return 'window exist'
  }

  it('should verify if window exist', () => {
    Object.defineProperty(global, 'window', {
      value: undefined,
    })
    expect(windowDependentFunction()).toEqual('window does not exist')
  })
Lianel
  • 101
  • 10