设置运行环境时的环境变量

时间:2019-12-13 09:29:28

标签: javascript node.js typescript unit-testing jestjs

我在main.ts上定义了此变量

const mockMode = process.env.MOCK_MODE;

我只是创建一个测试并将此变量设置为true,但主要不是'true',而是'false'

describe('onBook', () => {

    // Arrange
     const mockMode = "true";
     ...

1 个答案:

答案 0 :(得分:0)

您可以直接在单元测试用例中设置process.env.MOCK_MODE的值,并在最后将其恢复为原始值。

例如

main.ts

export function main() {
  const mockMode = process.env.MOCK_MODE;
  return mockMode;
}

main.test.ts

import { main } from './main';

describe('main', () => {
  it('should pass', () => {
    const original = process.env.MOCK_MODE;
    process.env.MOCK_MODE = 'true';
    const actual = main();
    expect(actual).toBe('true');
    process.env.MOCK_MODE = original;
  });
  it('should restore MOCK_MODE', () => {
    expect(process.env.MOCK_MODE).toBe('undefined');
  });
});

单元测试结果:

 PASS  src/stackoverflow/59319610/main.test.ts (14.207s)
  main
    ✓ should pass (7ms)
    ✓ should restore MOCK_MODE (1ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        16.293s