When working with Jest, it's important to remember that you can't use jest.mock(moduleName, factory, options) within a function scope - it should be used at the module scope instead. For function scope mocking, utilize jest.doMock(moduleName, factory, options).
Before running each test case, make sure to include jest.resetModules() to reset the module registry and clear the cache of all required modules.
This approach ensures that your ./config module registry is refreshed, providing different mocked values for each test case when requiring it post-jest.doMock('./config', () => {...}) declaration.
If you opt for the { virtual: true } option, it signifies that the express-request-proxy package isn't installed in your npm_modules directory. You can omit this option if the package is already installed.
For a unit test solution:
index.js
:
const router = require('express').Router({ mergeParams: true });
import config from './config';
import proxy from 'express-request-proxy';
router.get('', (...args) => {
console.log(config);
let query = {};
if (config.FOO === 'bar') {
query.baz = true;
}
return proxy({ url: '/stuff', query })(...args);
});
export default router;
config.js
:
export default {
FOO: '',
};
index.test.js
:
import request from 'supertest';
jest.mock('express-request-proxy', () => (data) => (req, res, next) => res.json(data), { virtual: true });
beforeEach(() => {
jest.resetAllMocks();
jest.resetModules();
});
describe('GET /', () => {
it('should get all stuff', () => {
jest.doMock('./config', () => ({}));
const router = require('./index').default;
const app = require('express')();
app.use(router);
return request(app)
.get('')
.expect(200)
.expect('Content-Type', /json/)
.then((response) => {
expect(response.body).toMatchSnapshot();
});
});
it('should get all stuff when FOO=bar', async () => {
jest.doMock('./config', () => ({
default: {
FOO: 'bar',
get: (key) => key,
},
__esModule: true,
}));
const router = require('./index').default;
const app = require('express')();
app.use(router);
await request(app)
.get('')
.expect(200)
.expect('Content-Type', /json/)
.then((response) => {
expect(response.body.query).toHaveProperty('baz');
});
});
});
Unit test outcomes with full coverage report:
PASS stackoverflow/61828748/index.test.js (11.966s)
GET /
✓ should get all stuff (8710ms)
✓ should get all stuff when FOO=bar (24ms)
console.log
{}
at stackoverflow/61828748/index.js:7:11
console.log
{ FOO: 'bar', get: [Function: get] }
at stackoverflow/61828748/index.js:7:11
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 1 passed, 1 total
Time: 13.268s
index.test.js.snap
:
// Jest Snapshot v1
exports[`GET / should get all stuff 1`] = `
Object {
"query": Object {},
"url": "/stuff",
}
`;
Source code available at: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61828748