Sometimes, we want to mock an exported const in Jest.
In this article, we’ll look at how to mock an exported const in Jest.
How to mock an exported const in Jest?
To mock an exported const in Jest, we can use the jest.mock
method.
For instance, we write:
const mockTrue = {
ENABLED: true
};
const mockFalse = {
ENABLED: false
};
describe('allowThrough', () => {
beforeEach(() => {
jest.resetModules();
});
test('success', () => {
jest.mock('./constants', () => mockTrue)
const {
ENABLED
} = require('./constants');
const {
allowThrough
} = require('./allowThrough');
expect(ENABLED).toBe(true);
expect(allowThrough({
value: 1
})).toBe(true);
});
test('fail, ENABLED === false', () => {
jest.mock('./constants', () => mockFalse)
const {
ENABLED
} = require('./constants');
const {
allowThrough
} = require('./allowThrough');
expect(ENABLED).toBe(false);
expect(allowThrough({
value: 1
})).toBe(false);
});
});
to mock the ./constants
with a function that returns the mocked exports.
Then can use the require the ./constants
with require
and get the ENABLED
exported member.
Jest will use the mocked version of that for the test since we called jest.mock
to mock it.
We use expect
to check that the mocked ENABLED
value it what we expect.
Conclusion
To mock an exported const in Jest, we can use the jest.mock
method.