Jarosław Wlazło
Jarosław Wlazło

Reputation: 370

Jest.js force window to be undefined

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?

Upvotes: 19

Views: 14648

Answers (3)

Lianel
Lianel

Reputation: 159

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')
  })

Upvotes: 3

trevorgk
trevorgk

Reputation: 1466

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

    

Upvotes: 20

Ben Winding
Ben Winding

Reputation: 11827

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

Upvotes: 7

Related Questions