使用JEST测试process.env值

时间:2019-06-11 15:10:50

标签: node.js jestjs

如果有以下情况,我有下一个配置文件:

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!'

开始

2 个答案:

答案 0 :(得分:0)

这是解决方案:

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

答案 1 :(得分:0)

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中,将AppEnv实例化为process.env.NODE_ENV

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
}