[英]Is there a way to mock `process.env.NODE_ENV` in my unit test using webpack and mocha?
I need to to mock in my unit test process.env.NODE_ENV
. 我需要在我的单元测试
process.env.NODE_ENV
进行模拟process.env.NODE_ENV
。
I am using webpack 2.0 for my build, jest-cli as build runner, and mocha and testing 我正在使用webpack 2.0作为构建版本,jest-cli作为构建运行器,以及mocha和测试
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
? 模拟
process.env.NODE
的正确方法是什么?
You should find after overriding the env vars you can run jest.resetModules();
你应该在重写env
jest.resetModules();
后找到你可以运行的jest.resetModules();
before you import the config. 在导入配置之前。 That should then load the config that reflects the expected
NODE_ENV
value. 然后应该加载反映预期
NODE_ENV
值的配置。
Without jest you can use the require-uncached module from npm to achieve the same effect. 如果没有开玩笑,您可以使用npm中的require-uncached模块来实现相同的效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.