【问题标题】:Test process.env value with JEST使用 JEST 测试 process.env 值
【发布时间】:2019-10-26 01:21:24
【问题描述】:

我有下一个 if 情况的配置文件:

if (!process.env.NODE_ENV) {
  throw Error('Process environment is required!')
}

const allowedEnvironments = ['local', 'development', 'production']

if (!allowedEnvironments.includes(process.env.NODE_ENV)) {
  throw Error('Process environment not allowed! Choose another!')
}

我如何为它编写测试? 我尝试过来自here 的变体。但是测试没有以错误'Process environment not allowed! Choose another!'开始

【问题讨论】:

标签: node.js jestjs


【解决方案1】:

解决办法如下:

index.ts:

function checkEnvironmentVars() {
  if (!process.env.NODE_ENV) {
    throw Error('Process environment is required!');
  }

  const allowedEnvironments = ['local', 'development', 'production'];

  if (!allowedEnvironments.includes(process.env.NODE_ENV)) {
    throw Error('Process environment not allowed! Choose another!');
  }
}

export { checkEnvironmentVars };

单元测试:

import { checkEnvironmentVars } from './';

const originalEnv = Object.assign({}, process.env);

describe('checkEnvironmentVars', () => {
  it('should throw error when NODE_ENV is not set', () => {
    delete process.env.NODE_ENV;
    expect(() => checkEnvironmentVars()).toThrowError(Error('Process environment is required!'));
  });

  it('should throw error when NODE_ENV is invalid', () => {
    process.env.NODE_ENV = 'stage';
    expect(() => checkEnvironmentVars()).toThrowError(Error('Process environment not allowed! Choose another!'));
  });

  it('should pass the check', () => {
    process.env.NODE_ENV = 'local';
    expect(() => checkEnvironmentVars()).not.toThrow();
  });
});

带有覆盖率报告的单元测试结果:

 PASS  src/stackoverflow/56546760/index.spec.ts
  checkEnvironmentVars
    ✓ should throw error when NODE_ENV is not set (8ms)
    ✓ should throw error when NODE_ENV is invalid (2ms)
    ✓ should pass the check

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |      100 |      100 |      100 |      100 |                   |
 index.ts |      100 |      100 |      100 |      100 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        3.651s

【讨论】:

    【解决方案2】:

    1) 你应该更好地封装你的检查:

    const allowedEnvironments = ['local', 'development', 'production'];
    
    class AppEnv {
      constructor(env) {
        if (!env) {
          throw Error('Process environment is required!');
        }
        if (!allowedEnvironments.includes(env)) {
          throw Error('Process environment not allowed! Choose another!');
        }
    
        this._env = env;
      }
    
      get isLocal() {
        return this._env === 'local';
      }
    
      get isDevelopment() {
        return this._env === 'development';
      }
    
      get isProduction() {
        return this._env === 'production';
      }
    }
    
    export { AppEnv };
    

    2) 然后你可以不用process.env为它写测试:

    import { AppEnv } from './app-env';
    
    describe('AppEnv', () => {
      const createAppEnv = (env: string) => new AppEnv(env);
    
      it('should throw for empty env', () => {
        expect(() => createAppEnv('')).toThrow();
      });
      it('should throw for bad env', () => {
        expect(() => createAppEnv('_bad_env_value_')).toThrow();
      });
      it('should be local', () => {
        expect(createAppEnv('local').isLocal).toBe(true);
      });
      it('should be development', () => {
        expect(createAppEnv('development').isDevelopment).toBe(true);
      });
      it('should be production', () => {
        expect(createAppEnv('production').isProduction).toBe(true);
      });
    });
    

    3) 在您的 config.js 中用 process.env.NODE_ENV 实例化 AppEnv

    import { AppEnv } from './app-env';
    
    const appEnv = new AppEnv(process.env.NODE_ENV);
    
    export { appEnv };
    

    4) 在您的应用程序中随处使用appEnv

    import { appEnv } from './config';
    
    if (appEnv.isDevelopment) {
      // do something
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-10
      • 1970-01-01
      • 2023-01-26
      • 2019-07-23
      • 2019-09-11
      • 2021-03-11
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      相关资源
      最近更新 更多