Dimitri Kopriwa
Dimitri Kopriwa

Reputation: 14363

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 ?

Upvotes: 6

Views: 9416

Answers (1)

muffinresearch
muffinresearch

Reputation: 380

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.

Upvotes: 4

Related Questions