0

I have a condition in my service file where

const RedisEnableCache = process.env.REDIS_ENABLE_CACHE || false

I have code for both condition in my service file,how can I cover both test file i.e true and false in my testcases. I have to write two test cases one with true condition and another with false.How do do that?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Does this answer your question? [test process.env with Jest](https://stackoverflow.com/questions/48033841/test-process-env-with-jest) – Emil Hotkowski Nov 20 '19 at 07:39

1 Answers1

1

Here is the unit test solution:

index.ts:

export function main() {
  const RedisEnableCache = process.env.REDIS_ENABLE_CACHE || false;
  if (RedisEnableCache === "true") {
    console.log("enable redis cache");
  } else {
    console.log("disable redis cache");
  }
}

index.spec.ts:

import { main } from "./";

describe("main", () => {
  const originalEnv = process.env.REDIS_ENABLE_CACHE;
  afterAll(() => {
    process.env.REDIS_ENABLE_CACHE = originalEnv;
    jest.restoreAllMocks();
  });
  it("should enable", () => {
    process.env.REDIS_ENABLE_CACHE = "true";
    const logSpy = jest.spyOn(console, "log");
    main();
    expect(logSpy).toBeCalledWith("enable redis cache");
  });

  it("should disable", () => {
    process.env.REDIS_ENABLE_CACHE = "false";
    const logSpy = jest.spyOn(console, "log");
    main();
    expect(logSpy).toBeCalledWith("disable redis cache");
  });
});

Unit test result with coverage report:

 PASS  src/stackoverflow/58948797/index.spec.ts
  main
    ✓ should enable (13ms)
    ✓ should disable (1ms)

  console.log node_modules/jest-mock/build/index.js:860
    enable redis cache

  console.log node_modules/jest-mock/build/index.js:860
    disable redis cache

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

Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58948797

Lin Du
  • 88,126
  • 95
  • 281
  • 483