test process.env with Jest

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

    Jest's setupFiles is the proper way to handle this, and you need not install dotenv, nor use an .env file at all, to make it work.

    jest.config.js:

    module.exports = {
      setupFiles: ["<rootDir>/.jest/setEnvVars.js"]
    };
    

    .jest/setEnvVars.js:

    process.env.MY_CUSTOM_TEST_ENV_VAR = 'foo'
    

    That's it.

    0 讨论(0)
  • 2020-11-28 04:04

    Expanding a bit on Serhan C.'s answer (https://stackoverflow.com/a/57944454/2708174)...

    according to this blog https://tekloon.dev/using-dotenv-with-jest you can include "dotenv/config" directly in setupFiles, without having to create and reference an external script that calls require("dotenv").config().

    i.e., simply do

    module.exports = {
        setupFiles: ["dotenv/config"]
    }
    
    0 讨论(0)
  • 2020-11-28 04:15

    In ./package.json:

    "jest": {
      "setupFiles": [
        "<rootDir>/jest/setEnvVars.js"
      ]
    }
    

    In ./jest/setEnvVars.js:

    process.env.SOME_VAR = 'value';
    
    
    0 讨论(0)
  • 2020-11-28 04:16

    In my opinion, it's much cleaner and easier to understand if you extract the retrieval of environment variables into a util (you probably want to include a check to fail fast if an environment variable is not set anyway), then you can just mock the util.

    // util.js
    exports.getEnv = (key) => {
        const value = process.env[key];
        if (value === undefined) {
          throw new Error(`Missing required environment variable ${key}`);
        }
        return value;
    };
    
    // app.test.js
    const util = require('./util');
    jest.mock('./util');
    
    util.getEnv.mockImplementation(key => `fake-${key}`);
    
    test('test', () => {...});
    
    0 讨论(0)
  • 2020-11-28 04:18

    Another option is to add it to the jest.config.js file after the module.exports definition:

    process.env = Object.assign(process.env, {
      VAR_NAME: 'varValue',
      VAR_NAME_2: 'varValue2'
    });
    

    This way it's not necessary to define the ENV variables in each .spec file and they can be adjusted globally.

    0 讨论(0)
  • 2020-11-28 04:22

    I think you could try this too:

    const currentEnv = process.env;
    process.env = { ENV_NODE: 'whatever' };
    
    // test code...
    
    process.env = currentEnv;
    

    This works for me and you don't need module things

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