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?
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).
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.
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.
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', () => {
...
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With