Manual Mocks
You can create __mocks__
directory in the same level as utilities.js
and then create a file with name utilities.js
inside this directory.
utilities.js
const speak = () => "Function speak";
const add = (x, y) => x + y;
const sub = (x, y) => x - y;
module.exports = { speak, add, sub };
Now, keep everything as is and just mock the speak
function.
__mocks__/utilities.js
const speak = jest.fn(() => "Mocked function speak");
const add = (x, y) => x + y;
const sub = (x, y) => x - y;
module.exports = { speak, add, sub };
And now you can mock utilities.js
utilities.test.js
const { speak, add, sub } = require("./utilities");
jest.mock("./utilities");
test("speak should be mocked", () => {
expect(speak()).toBe("Mocked function speak");
});
Mocking Node Modules
Create a directory named __mocks__
in the same level as node_modules
and add a file 'axios.js' inside this directory.
__mocks__/axios.js
const axios = {
get: () => Promise.resolve({ data: { name: "Mocked name" } }),
};
module.exports = axios;
fetch.js
const axios = require("axios");
const fetch = async () => {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/users/1"
);
return data.name;
};
module.exports = fetch;
With node modules you don't need to explicitly call jest.mock("axios")
.
fetch.test.js
const fetch = require("./fetch");
test("axios should be mocked", async () => {
expect(await fetch()).toBe("Mocked name");
});
jest.mock()
actually gets hoisted like variables. As a result, they're called before the imports.