test process.env with Jest

后端 未结 9 1967
南笙
南笙 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(...
    

提交回复
热议问题