McShaman
McShaman

Reputation: 3995

what is the best way to reset Node's global variable for each test?

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

Answers (1)

Pavlo Sobchuk
Pavlo Sobchuk

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

Related Questions