Karen
Karen

Reputation: 1429

How to mock a variable inside a Jest test function?

I'm testing the Express application with Jest and came across a slight problem - the module uses variable that is initialized before the test execution, here is my app.js file:

const app = express();
const isDev = process.env.NODE_ENV === 'development';

app.get('*', (req, res, next) => {
  if (isDev) {
    res.status(404).json({ error: 'Wrong URL' });
  } else {
    res.sendFile(path.join(__dirname, '../index.html'));
  }
});

app.use(errorHandler);

module.exports = app;

When I run Jest tests, my process.env.NODE_ENV is equal to test, that's why I can't cover the first if condition, where isDev is true. I've tried to reassign process.env.NODE_ENV before the test request - it works, but as isDev variable initialization has been done before test execution, it didn't work.

This is my test:

const request = require('supertest');
const app = require('../app');

describe('GET /*', () => {
  const OLD_ENV = process.env;

  beforeEach(() => {
    // Clear JEST cache
    jest.resetModules();
    process.env = { ...OLD_ENV };
    Reflect.deleteProperty(process.env, 'NODE_ENV');
  });

  test('Not existing path (development env) - 404 status', async () => {
    process.env.NODE_ENV = 'development';

    const response = await request(app).
      get('/wrongUrl');
    expect(response.status).toBe(404);

  });

});

How can I mock the isDev variable inside my test?

Upvotes: 3

Views: 5437

Answers (2)

Lucas Fabre
Lucas Fabre

Reputation: 1951

You could create an .env file just for testing. If you are using express you could also use dotenv. With this package you can import env variables from different files.

Just add this line at the top of your file.

require('dotenv').config({ path: process.cwd() + '/path/to/test.env' });

This way you can always change the env variables you want to use, before every test.

Upvotes: 0

Teneff
Teneff

Reputation: 32148

you can use jest.isolateModules(fn) to app in isolation like this:

describe("GET /*", () => {
  describe("on development", () => {
    let app;
    beforeAll(() => {
      process.env.NODE_ENV = "development";
      jest.isolateModules(() => {
        app = require("../app");
      });
    });

    it("should to this", () => {
      expect(app).....
    });
  });

  describe("on production", () => {
    let app;
    beforeAll(() => {
      process.env.NODE_ENV = "production";
      jest.isolateModules(() => {
        app = require("../app");
      });
    });

    it("should to that", () => {
      expect(app())....
    });
  });
});

Upvotes: 2

Related Questions