Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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 ?

like image 373
Dimitri Kopriwa Avatar asked Mar 13 '17 10:03

Dimitri Kopriwa


People also ask

Does jest set Node_env?

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.

What is process env Node_env?

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).


1 Answers

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.

like image 173
muffinresearch Avatar answered Nov 15 '22 12:11

muffinresearch