MasterOfTheHouse
MasterOfTheHouse

Reputation: 1339

Jest test in NodeJS with global variable failing because its value has already being set for another test

I'm working on a typescript project using node and jest. I need to test a function that can or can not modify a global variable. I need help resetting the global variable( a typescript Map) because once it has been modified by one test it remains set with the old value and the new test does work.

file1.ts


let impCache: Map<sint, string>

export function functionToTest(string, number){
    doALotOfThings()
    ChecksAndReturnExceptionEct()
    if (!impCache){
     AtSomePointCouldModify_impCache()
    }
    doMoreStuff()
}

file1.test.ts

describe('All tests'){
    describe('this test1 never change impCache', ()=>{
        it('does its works', () => {
            assert('all_is_ok').tobe(string)
        })
    })

    describe('this test2 never change impCache', ()=>{
        it('does its works', () => {
            assert('all_is_ok').tobe(string)
        })
    })

    describe('this test3 changes impCache', ()=>{
        it('does its works', () => {
            assert('all_is_ok').tobe(string)
        })
    })

    describe('this test4 changes impCache', ()=>{
        it('does its works', () => {
            assert('this always fail when run with all test but succeeds alone, because the cache was already set by the previous test ').tobe(string)
        })
    })
}

What can I do to clear the value impCache variable, so test4 does not see impCache value that has already been set by test3 ?

BR

Upvotes: 0

Views: 1700

Answers (2)

MasterOfTheHouse
MasterOfTheHouse

Reputation: 1339

The solution is to create a sandbox using jest.isolateModules

This is a fantastic solution to a complex scenario you see time and again in the real world.

Kudos to the jest team !!

Upvotes: 1

geofh
geofh

Reputation: 605

As far as I can see you do not expose the cache nor any function that could clear it. If it were a Redis cache or something then you would be able to clear it with some endpoint, but if it's in-memory you can't do anything unless you expose such a utility. I'd suggest you do just that, for the purpose of the tests ... for example a function called clearCache. Then you can simply put this in your test suite:

beforeEach(clearCache);

It makes sense to run each test in a clean environment, using some mechanism like this, so that each is independent of other tests.

Upvotes: 0

Related Questions