1

I'm trying to unit test a function in my application that checks the value of process.env.NODE_ENV. FWIW the type of process.env.NODE_ENV is string | undefined.

In my jest test, I can easily test string values when it's set like this:

it('test', () => {
  // Arrange
  process.env.NODE_ENV = 'development';

  // Act
  functionUnderTest();

  // Assert
  export(true).toBe(true);
});

The problem arises when I want to test my code's handling of process.env.NODE_ENV being set to undefined. I would expect to be able to simply set process.env.NODE_ENV = undefined in my jest test. Unfortunately, it would seem that somewhere along the line, the value is converted to a string such that when the test hits my function, the value of process.env.NODE_ENV is "undefined" (as a string).

I've also tried to set process.env.NODE_ENV to undefined like this, but with the same result:

process.env = Object.assign(process.env, { NODE_ENV: undefined });

How can I set process.env.NODE_ENV to undefined in a jest test?

Lin Du
  • 88,126
  • 95
  • 281
  • 483
mellis481
  • 4,332
  • 12
  • 71
  • 118
  • Does this answer your question? [Test process.env with Jest](https://stackoverflow.com/questions/48033841/test-process-env-with-jest) – jonrsharpe Mar 24 '21 at 23:39

2 Answers2

0

Just delete the process.env.NODE_ENV.

E.g.

function functionUnderTest() {
  return process.env.NODE_ENV;
}

describe('66787053', () => {
  it('test', () => {
    process.env.NODE_ENV = 'development';
    const actual = functionUnderTest();
    expect(actual).toBe('development');
  });

  it('should pass', () => {
    delete process.env.NODE_ENV;
    const actual = functionUnderTest();
    expect(actual).toBeUndefined();
  });
});

test result:

 PASS  examples/66787053/index.test.js (6.951 s)
  66787053
    ✓ test (2 ms)
    ✓ should pass

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        9.061 s
Lin Du
  • 88,126
  • 95
  • 281
  • 483
0

This worked for me . In package.json

  "jest": {
    "rootDir": "./src",
    "setupFiles": [
      "<rootDir>/jest.env.js"
    ]
  }

and the src/jest.env.js looks like

process.env.REGION = 'us-west-2'
SRC
  • 435
  • 4
  • 5