Mocking in Jest means replacing a real function, module, or API call with a fake implementation to control behavior in tests. It allows you to test components in isolation without relying on actual network calls or external dependencies.
1️⃣ Why We Mock
- Isolate Tests: Focus on the component logic, not external APIs
- Control Responses: Simulate success, failure, or edge cases
- Improve Test Performance: Avoid slow network or database calls
- Avoid Side Effects: Prevent real HTTP requests or file system changes
2️⃣ Mocking a Function
const fetchData = jest.fn(); // mock function
fetchData.mockReturnValue("Hello World");
console.log(fetchData()); // "Hello World"
expect(fetchData).toHaveBeenCalledTimes(0); // check call count
3️⃣ Mocking an API Call (Module)
Example: Using axios
// api.js
import axios from "axios";
export const getUsers = () => axios.get("/users");
// api.test.js
import { getUsers } from "./api";
import axios from "axios";
jest.mock("axios"); // mock the axios module
test("fetch users", async () => {
const users = [{ id: 1, name: "Alice" }];
axios.get.mockResolvedValue({ data: users });
const result = await getUsers();
expect(result.data).toEqual(users);
expect(axios.get).toHaveBeenCalledWith("/users");
});
Explanation:
jest.mock("axios")→ replacesaxioswith a mockmockResolvedValue→ simulates a successful API response- Can also use
mockRejectedValuefor errors
4️⃣ Mocking Modules with Custom Implementation
jest.mock("./utils", () => ({
generateId: jest.fn(() => "12345"),
}));
- Replaces the
generateIdfunction with a custom implementation
⚡ Key Points:
- Mocking allows predictable and isolated tests
- Useful for functions, modules, timers, and network requests
- Use
jest.fn(),jest.mock(), and mock return values
In short:
We mock in Jest to control external dependencies, simulate different scenarios, and ensure tests run fast and reliably.