test process.env with Jest

后端 未结 9 1968
南笙
南笙 2020-11-28 04:00

I have an app that depends on environmental variables like:

const APP_PORT = process.env.APP_PORT || 8080;

and I would like to test that fo

9条回答
  •  情书的邮戳
    2020-11-28 04:28

    The way I did it can be found in this SO question.

    It is important to resetModules before each test and then dynamically import the module inside the test:

    describe('environmental variables', () => {
      const OLD_ENV = process.env;
    
      beforeEach(() => {
        jest.resetModules() // most important - it clears the cache
        process.env = { ...OLD_ENV }; // make a copy
      });
    
      afterAll(() => {
        process.env = OLD_ENV; // restore old env
      });
    
      test('will receive process.env variables', () => {
        // set the variables
        process.env.NODE_ENV = 'dev';
        process.env.PROXY_PREFIX = '/new-prefix/';
        process.env.API_URL = 'https://new-api.com/';
        process.env.APP_PORT = '7080';
        process.env.USE_PROXY = 'false';
    
        const testedModule = require('../../config/env').default
    
        // ... actual testing
      });
    });
    

    If you look for a way to load env values before running the Jest look for the answer below. You should use setupFiles for that.

提交回复
热议问题