How to mock environment variable check from function initialization before test?

0

Issue

I have a decorator function that gets some data from environment variable. So in the beginning I check that this environment variable is set.

function dec(target: Object, key: string | symbol, descriptor: PropertyDescriptor) {
  if (!process.env.NAMESPACE) {
    throw new Error('The environment variable NAMESPACE was not set.');
  }
  ...
}

Then I use this decorator for a function.

@dec
function foo() {
...
}

I try to test function foo() with jest unit tests. The test fails if I didn’t set NAMESPACE variable on my laptop. If I try to set it up in beforeAll section it still fails. Somehow function dec is called earlier than beforeAll. How to set up NAMESPACE variable in test earlier than dec is called?

Solution

In jest, you can configure a setup file that is ran before tests & before jest hooks ("beforeAll / beforeEach").

In jest.config.js (or .ts) you have a setupFiles property.

You just have to add in jest.config.js :

{
    ...
    setupFiles: ['<rootDir>/jest.setup.js'],
}

Inside jest.setup.js, just add all your env variables for testing purpose :

process.env.NAMESPACE = 'Test-Namespace';

You can eventually use setupFilesAfterEnv property is needed. The order is :
setupFiles > setupFilesAfterEnv > beforeAll > beforeEach > afterEach > afterAll

Answered By – Robin Michay

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More