Jest:Mock
lastmod 2026-11-10created 2022-04-113 edits
Jest:Mock is a page summarizing the mocking features of Jest, a JavaScript testing framework. jest.mock() replaces an entire module with a fake implementation, jest.fn() creates a mock function that records its calls, and mockResolvedValue or mockRejectedValue specifies asynchronous results. It is used to make tests deterministic by removing external API calls and network dependencies.
Example
import axios from "axios";
import { BASE_URL, fetchUsers } from "./utils";
jest.mock("axios");
describe("fetchUsers", () => {
describe("when API call is successful", () => {
it("should return users list", async () => {
// given
const users = [
{ id: 1, name: "John" },
{ id: 2, name: "Andrew" },
];
axios.get.mockResolvedValueOnce(users);
// when
const result = await fetchUsers();
// then
expect(axios.get).toHaveBeenCalledWith(`${BASE_URL}/users`);
expect(result).toEqual(users);
});
});
describe("when API call fails", () => {
it("should return empty users list", async () => {
// given
const message = "Network Error";
axios.get.mockRejectedValueOnce(new Error(message));
// when
const result = await fetchUsers();
// then
expect(axios.get).toHaveBeenCalledWith(`${BASE_URL}/users`);
expect(result).toEqual([]);
});
});
});