Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 264
Jarosław Wlazło Avatar asked Jul 19 '18 14:07

Jarosław Wlazło


People also ask

Can JavaScript undefined Windows?

Is there ever a case when the window. document object is null or undefined? Yes, for JavaScript code that isn't in a document (e.g. node. js).

Does Jest use jsdom?

Jest actually ships with jsdom and the environment already configured. You can override it with the testEnvironment setting. If you need to set up more aspects of the environment though, you can use the setupTestFrameworkScriptFile setting to point to a file that executes before all of your tests run.

What is jest environment Jsdom?

jsdom is a pure JavaScript implementation of the DOM and browser APIs that runs in node. If you're not using Jest and you would like to run your tests in Node, then you must install jsdom yourself. There's also a package called global-jsdom which can be used to setup the global environment to simulate the browser APIs.


1 Answers

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

    
like image 66
trevorgk Avatar answered Sep 19 '22 13:09

trevorgk