Reputation: 639
I am trying to force some environment variables from the Jest testcase such that during execution, the code should take the proper path:
Basically my class-under-test looks like:
const myProvider =
process.env.IS_LOCAL == 'true' ? localProvider : process.env.IS_MOCK == 'true' ? mockProvider : realProvider;
So basicaly I want to pickup the mockProvider by forcing the IS_MOCK as true.
These are the two things I have tried:
Adding a setup file setup.ts
process.env.IS_MOCK = 'true'
process.env.IS_LOCAL = 'false'
In the jest config:
setupFiles: ['<rootDir>/setup.ts'],
Setting up the value from the test file:
const env = process.env
beforeAll(async () => {
jest.resetModules()
process.env = {
...env,
IS_LOCAL: 'false', //
IS_MOCK: 'true',
};
afterAll(async () => {
process.env = env;
});
None of these actually works here.
Any help would be good.
Upvotes: 0
Views: 801
Reputation: 639
The only way it worked for me is to read the correct .env file in the test configuration itself.
This is my jest config
file:
const dotEnv = require('dotenv');
dotEnv.config({ path: envFilePath_starting_from_where_jest_is_running });
console.log(`Running Jest with env: ${process.env.<your-env-variable>}`);
module.exports = {
....
}
Just install the dotenv
as dev dependencies: npm install --save-def dotenv
.
Then inside the Jest tests, one can check the env variable as:
const correctProvider: process.env.MOCK_ENV ? mockService : concreteService;
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule]
})
.overrideProvider(Service)
.useValue(correctProvider)
.compile();
That's the best way I can do it.
Upvotes: 1