I need to to mock in my unit test process.env.NODE_ENV
.
I am using webpack 2.0 for my build, jest-cli as build runner, and mocha and testing
import { ENV } from '../index';
describe('environments configuration', () => {
describe('default environment', () => {
let config;
beforeAll(() => {
delete process.env.NODE_ENV;
process.env.NODE_ENV = ENV.DEFAULT;
config = require('../index');
});
it('should be default login url', () => {
expect(config.url.login).toEqual('http://localhost:8080/login');
});
it('should store token in local storage', () => {
expect(config.STORAGE.TOKEN.type).toEqual('localStorage');
});
});
describe('development environment', () => {
let config;
beforeAll(() => {
delete process.env.NODE_ENV;
process.env.NODE_ENV = ENV.DEVELOPMENT;
config = require('../index');
});
it('should be development login url', () => {
expect(config.url.login).toEqual('https://dev.localhost.com/login');
});
it('should store token in local storage', () => {
expect(config.STORAGE.TOKEN.type).toEqual('localStorage');
});
});
describe('production environment', () => {
let config;
beforeAll(() => {
delete process.env.NODE_ENV;
process.env.NODE_ENV = ENV.PRODUCTION;
config = require('../index');
});
it('should be production login url', () => {
expect(config.url.login).toEqual('https://localhost.com/login');
});
it('should store token in session storage', () => {
expect(config.STORAGE.TOKEN.type).toEqual('sessionStorage');
});
});
});
Unfortunately, this doesn't seems to do the trick, I always have the default config loaded first.
I have found this plugin that could eventually do the trick.
Almost none is using so I wonder:
What is the correct way to mock the process.env.NODE
?
Jest automatically defines environment variable NODE_ENV as test (see https://jestjs.io/docs/environment-variables), as you can confirm from your error message: console.
NODE_ENV is an environment variable that stands for node environment in express server. The NODE_ENV environment variable specifies the environment in which an application is running (usually, development or production).
You should find after overriding the env vars you can run jest.resetModules();
before you import the config. That should then load the config that reflects the expected NODE_ENV
value.
Without jest you can use the require-uncached module from npm to achieve the same effect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With