Mocking replaces a dependency or functionality with a controlled substitute whose behavior the test specifies. It isolates React components from callbacks, browser APIs, application context, and external services while allowing success, failure, loading, and invocation behavior to be tested deterministically. section 10.3 section 10.3.1
Choose the replacement boundary according to the behavior under test:
- Mock a callback with vi.fn(), then assert that it was called with the expected argument. section 10.2.2
- Replace a browser API such as navigator.geolocation with an object containing a controlled mock function, then drive success and error paths. section 10.3.1
- Mock a complete library such as Axios to avoid slow external requests, prevent rate-limit issues, and force loading or failure states. section 10.3.2
- Prefer Mock Service Worker for networking scenarios when testing the API layer; library mocks remain useful for focused component isolation. section 10.3.2
Testing a controlled geolocation response
A WhereAmI component calls navigator.geolocation.getCurrentPosition when the user clicks “Where am I?”. The test replaces that method with vi.fn(), configures it to invoke either the success or error callback, performs the click with userEvent, and checks the resulting coordinates or error heading. section 10.3.1
Listing 10.9 Testing the items component from a Todo app
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import "@testing-library/jest-dom";
import { vi } from "vitest";
import { Items } from "./Items";
test("Items should call onDelete callback
when item is deleted", async () => {
// ARRANGE
const items = ["Item A", "Item B"];
const mockDelete = vi.fn(); #1
render( #2
<Items items={items} onDelete={mockDelete} />, #2
);
// ACT
const user = userEvent.setup();
const secondItemDelete = screen.getByRole("button", {
name: "Delete 'Item B'",
});
await user.click(secondItemDelete); #3
// ASSERT
expect(mockDelete) #4
.toHaveBeenCalledWith("Item B"); #4
});
A runnable React Testing Library and Vitest test demonstrates creating a mock callback, rendering Items, clicking the second delete button, and asserting the callback argument. section 10.2.2




















