test process.env with Jest

后端 未结 9 1915
南笙
南笙 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:23

    Depending on how you can organize your code, another option can be to put the env variable within a function that's executed at runtime.

    In this file, the env var is set at import time, and requires dynamic requires in order to test different env vars (as described in this answer):

    const env = process.env.MY_ENV_VAR;
    
    const envMessage = () => `MY_ENV_VAR is set to ${env}!`;
    
    export default myModule;
    

    In this file, the env var is set at envMessage execution time, and you should be able to mutate process.env directly in your tests:

    const envMessage = () => {
      const env = process.env.MY_VAR;
      return `MY_ENV_VAR is set to ${env}!`;
    }
    
    export default myModule;
    

    Jest test:

    const vals = [
      'ONE',
      'TWO',
      'THREE',
    ];
    
    vals.forEach((val) => {
      it(`Returns the correct string for each ${val} value`, () => {
        process.env.MY_VAR = val;
    
        expect(envMessage()).toEqual(...
    
    0 讨论(0)
  • 2020-11-28 04:24

    You can use setupFiles feature of jest config. As documentation said that,

    A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.

    1. npm install dotenv dotenv that uses to access env variable.
    2. Create your .env file to root directory of your application and add this line into it.
    #.env
    APP_PORT=8080
    
    1. Create your custom module file as It name being someModuleForTest.js and add this line into it.
    //someModuleForTest.js
    require("dotenv").config()
    
    1. Update your jest.config.js file like this
    module.exports = {
      setupFiles: ["./someModuleForTest"]
    }
    
    1. You can access env's variable within all test blocks.
    test("Some test name", () => {
      expect(process.env.APP_PORT).toBe("8080")
    })
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题