Reputation: 3995
I have some Jest tests that only pass after another test run before it. When I look at the global variable I can see it is retaining values between tests which seems to be impacting the suite. I cannot find any documentation around best practices regarding managing the global variable (sometimes called window or globalThis).
I have seen some examples of the following in my code base:
const globalAny = global;
beforeEach(() => {
globalAny.window = Object.create(global);
});
afterEach(() => {
globalAny.window = globalAny;
});
This appears to work but I wonder if this is the best approach? Seems surprising there isn't more information about this (maybe Im searching the wrong search terms).
Upvotes: 1
Views: 136
Reputation: 1564
The approach is generally valid, though I would also consider using "setupFilesAfterEnv"
property.
https://jestjs.io/docs/configuration#setupfilesafterenv-array
And I also usually do the following in that file:
// jest.setup.js
beforeEach(() => {
// Reset `window` to an empty object before each test to ensure isolation
global.window = {};
});
afterEach(() => {
// Clean up after each test
delete global.window;
});
Upvotes: 2