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

Time:12-21

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?

CodePudding user response:

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

  • Related