Categories
JavaScript Answers

How to test process.env with Jest?

Spread the love

Sometimes, we want to test process.env with Jest.

In this article, we’ll look at how to test process.env with Jest.

How to test process.env with Jest?

To test process.env with Jest, we can set the process.env properties before out tests.

And then we can run the test code after that.

For instance, we write

describe('environmental variables', () => {
  const OLD_ENV = process.env;

  beforeEach(() => {
    jest.resetModules()
    process.env = {
      ...OLD_ENV
    };
  });

  afterAll(() => {
    process.env = OLD_ENV;
  });

  test('will receive process.env variables', () => {
    process.env.NODE_ENV = 'dev';
    process.env.PROXY_PREFIX = '/new-prefix/';
    process.env.API_URL = 'https://new-api.com/';
    process.env.APP_PORT = '7080';
    process.env.USE_PROXY = 'false';

    // tests
  });
});

to reset process.env to the old values in the beforeEach callback.

And after each test, we set process.env to OLD_ENV which has the original process.env values.

Next, we set the process.env values we want to run our test with within the test callback.

And then we run our test code after they’re set.

Conclusion

To test process.env with Jest, we can set the process.env properties before out tests.

And then we can run the test code after that.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *