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?