0

Azure function test(using jest) failed because of "process.env variable undefined". the existing code working perfectly in normal debug, but in the "yarn run jest" command, it is showing the process.env variable undefined. Every configurations are stored in local.settings.json.

I have tried "test process.env with Jest" this link. but my production server cannot accept multiple declarations

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Athulya
  • 181
  • 1
  • 13

1 Answers1

1

You can use jest.resetModules() in beforeEach method to reset the already required modules

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

Here you can find a complete guide on the same.

https://jestjs.io/docs/en/jest-object.html#jestresetmodules

Link you posted is an ideal way of doing it by creating implementation like below

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

  beforeEach(() => {
    jest.resetModules() // this is important
    process.env = { ...OLD_ENV };
    delete process.env.NODE_ENV;
  });

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

  test('will receive process.env variables', () => {
    // set the 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';

    const testedModule = require('../../config/env').default

    // ... actual testing
  });
});

Hope it helps.

Mohit Verma
  • 5,140
  • 2
  • 12
  • 27
  • 1
    Thanks for your reply, But in my code, I don't have any .env file. it will take from "local.settings.json" file. so how can I connect with that? – Athulya Apr 24 '19 at 12:00