Sometimes, we want to mock an exported constant in Jest and JavaScript.
In this article, we’ll look at how to mock an exported constant in Jest and JavaScript.
How to mock an exported constant in Jest and JavaScript?
To mock an exported constant in Jest and JavaScript, we can mock the imported modules with jest.mock
.
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 call jest.mock
in each test with the module path and a function that returns the content of the module.
Then we call expect
to check for the result we’re looking for in each test.
In the beforeEach
callback, we call jest.resetModules
to reset the modules to their original values.
Conclusion
To mock an exported constant in Jest and JavaScript, we can mock the imported modules with jest.mock
.