Reputation: 370
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
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
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
Reputation: 11827
Here's what I did to force window
to be undefined, during selected jest tests.
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
});
If you need the window
object, simply remove that statement at the top.
Upvotes: 7