Skip to content
Advertisement

Invalidate node cache when using Jest

I have a file with object that gets populated with process.env properties:

env.js

JavaScript

Now I try to test this file with different process.env properties:

env.test.js

JavaScript

Unfortunately, even though I try to load the file in every test separately the file gets loaded only once, making the third test fail with:

JavaScript

P.S. It doesn’t fail when I run the test alone.

I also know that env.js loads only once because console.log('LOADING env.js'); gets fired only once.

I tried to invalidate Nodes cache like:

JavaScript

but require.cache is empty {} before each test so it seems that Jest is somehow responsible for importing the file.

I also tried to run yarn jest --no-cache but didn’t help.

So what I want is to load env.js before each test so I can test how it behaves with different node environmental variables.

jest@^22.0.4

Advertisement

Answer

You can use jest.resetModules() in beforeEach method to reset the already required modules

JavaScript
Advertisement