Skip to content
ClapelloNotes by Barath
ReactCh 13 · 6/6
Core5 min readUpdated

React / 75

Faking the outside world: fetch, Router and Redux

TL;DR

Replace fetch with a mock, wait for results with findBy, and wrap components in the same providers your app uses, with a fresh store per test.

Mocking fetch

src/components/Menu.jsx
import { useEffect, useState } from "react";
 
export default function Menu() {
  const [dishes, setDishes] = useState(null);
 
  useEffect(() => {
    fetch("https://dummyjson.com/recipes?limit=10")
      .then((res) => res.json())
      .then((data) => setDishes(data.recipes));
  }, []);
 
  if (!dishes) return <p>Loading…</p>;
  return <ul>{dishes.map((d) => <li key={d.id}>{d.name}</li>)}</ul>;
}

The test swaps the global fetch for a mock function that returns fake data instantly:

import { render, screen } from "@testing-library/react";
import Menu from "./Menu";
 
const fakeData = { recipes: [{ id: 1, name: "Veg Burger" }, { id: 2, name: "Paneer Pizza" }] };
 
beforeEach(() => {
  vi.stubGlobal("fetch", vi.fn(async () => ({ ok: true, json: async () => fakeData })));
});
afterEach(() => {
  vi.unstubAllGlobals();
});
 
test("shows dishes from the API", async () => {
  render(<Menu />);
  expect(screen.getByText("Loading…")).toBeInTheDocument();
 
  expect(await screen.findByText("Veg Burger")).toBeInTheDocument();
  expect(screen.getAllByRole("listitem")).toHaveLength(2);
  expect(fetch).toHaveBeenCalledTimes(1);
});
import { render, screen } from "@testing-library/react";
import Menu from "./Menu";
 
const fakeData = { recipes: [{ id: 1, name: "Veg Burger" }, { id: 2, name: "Paneer Pizza" }] };
 
beforeEach(() => {
  global.fetch = jest.fn(() =>
    Promise.resolve({ ok: true, json: () => Promise.resolve(fakeData) })
  );
});
 
test("shows dishes from the API", async () => {
  render(<Menu />);
  expect(screen.getByText("Loading…")).toBeInTheDocument();
 
  expect(await screen.findByText("Veg Burger")).toBeInTheDocument();
  expect(screen.getAllByRole("listitem")).toHaveLength(2);
  expect(fetch).toHaveBeenCalledTimes(1);
});

The mock only needs the parts your code uses: an object with a json() method that resolves to your data. A fresh mock in beforeEach means call counts start at zero for every test.

Waiting for async updates

0 ms · render(<Menu />)

Loading…

the effect calls fetch, which is your mock
await screen.findByText("Veg Burger")

findBy retries

0 ms · not yet50 ms · not yet100 ms · not yet150 ms · not yetfound ✓
mock resolved → setDishes → re-render

promise resolves

Your next expect() runs

expect(await screen.findByText(…)).toBeInTheDocument()
findBy keeps re-checking the DOM (every 50 ms by default) until the element appears, or gives up after 1000 ms and fails the test.
ToolUse it to
await screen.findByText("Veg Burger")Wait for an element to appear
await waitFor(() => expect(fetch).toHaveBeenCalled())Retry any assertion until it passes
await waitForElementToBeRemoved(() => screen.queryByText("Loading…"))Wait for something to disappear

Import waitFor and waitForElementToBeRemoved from @testing-library/react. All three give up after 1000 ms by default.

Wrapping Router and Redux

<Provider store={freshStore}>

for useSelector / useDispatch · a new store per test

<MemoryRouter initialEntries={["/"]}>

for <Link>, useNavigate, useParams

<Header />

the component under test
In the app, main.jsx wraps everything in providers. A test renders one component on its own, so it must add the same wrappers itself.

Make one helper that recreates your app's providers, with a new store for every test:

src/test/renderWithProviders.jsx
import { render } from "@testing-library/react";
import { configureStore } from "@reduxjs/toolkit";
import { Provider } from "react-redux";
import { MemoryRouter } from "react-router";
import cartReducer from "../store/cartSlice";
 
export function renderWithProviders(ui, { preloadedState, route = "/" } = {}) {
  const store = configureStore({ reducer: { cart: cartReducer }, preloadedState });
 
  function Wrapper({ children }) {
    return (
      <Provider store={store}>
        <MemoryRouter initialEntries={[route]}>{children}</MemoryRouter>
      </Provider>
    );
  }
  return { store, ...render(ui, { wrapper: Wrapper }) };
}
src/components/Header.test.jsx
import { screen } from "@testing-library/react";
import { renderWithProviders } from "../test/renderWithProviders";
import Header from "./Header";
 
test("shows how many items are in the cart", () => {
  renderWithProviders(<Header />, {
    preloadedState: { cart: { items: [{ id: 1, name: "Veg Burger", qty: 2 }] } },
  });
  expect(screen.getByRole("link", { name: "Cart (2)" })).toHaveAttribute("href", "/cart");
});

Use a real store with your real reducers, not a mocked useSelector: then the test also checks that your slice and selectors work together. MemoryRouter keeps the URL in memory, so tests never touch the browser's address bar; initialEntries sets the starting page.

Gotchas

Recall

Can you answer these?

0/5

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.