Skip to main content

Testing

A small todo list and five tests for it. The tests render the component with Testing Library and answer its requests with setMock, so they run without a server and cover loading, success, error, empty and save states.

intermediatetestingmockinguseFetchuseSubmit
import { createClient } from "@hyper-fetch/core";

export const client = createClient({ url: "https://dummyjson.com" });

export type Todo = { id: number; todo: string; completed: boolean; userId: number };

/**
* Export the exact request the component uses. `setMock` changes only the instance it is called on, and a request
* derived from it earlier (for example with `setQueryParams`) would keep going to the network in tests.
*/
export const getTodosRequest = client
.createRequest<{
response: { todos: Todo[]; total: number };
queryParams: { limit: number };
}>()({ endpoint: "/todos" })
.setQueryParams({ limit: 5 });

export const updateTodoRequest = client.createRequest<{ response: Todo; payload: Pick<Todo, "completed"> }>()({
endpoint: "/todos/:todoId",
method: "PATCH",
});
Run locallynpx tiged BetterTyped/hyper-fetch/examples/react/testing hyper-fetch-react-testing && cd hyper-fetch-react-testing && npm install && npm run dev
What it shows
  1. setMock answers a request in tests. Cache, hooks and callbacks run the same way as with a real response.
  2. Error and edge states: a mock that returns error and a status tests the error message without a failing server.
  3. Checking what was sent: the mock receives the request, so a test can assert the payload.
  4. Isolation: clearMock() and client.clear() after each test, so no test sees another test's data.

How it works​

  1. TodoList.tsx is an ordinary component: useFetch(getTodosRequest) loads the list and useSubmit(updateTodoRequest) saves a checkbox. It knows nothing about tests.

  2. Each test attaches a mock to the request before it renders:

    getTodosRequest.setMock(() => ({ data: { todos, total: 2 }, status: 200 }));
    render(<TodoList />);
    expect(await screen.findByLabelText("Write the tests")).toBeTruthy();

    The mock replaces the adapter only. The request still goes through the dispatcher and the cache, so the test checks the same code path the app uses.

  3. A failure is a mock with error and a status. submit() and send() resolve with the failed response, they do not throw, so the component shows its error message and the test reads it.

  4. The save test reads request.payload inside the mock and checks that the component sent { completed: true }.

  5. afterEach calls cleanup(), removes the mocks with clearMock() and resets the cache and queues with client.clear().

  6. api.ts exports the request with its query params already set, and the component uses that exact object. setMock changes only the instance it is called on. A request derived earlier with setQueryParams() or setParams() keeps its own copy and would still go to the network. Requests derived later, such as the one submit({ params }) builds, copy the mock.

Run the tests​

The preview runs the app against dummyjson. To run the tests, open a terminal in StackBlitz or CodeSandbox, or in your local copy, and run:

npm test

vitest.config.ts sets environment: "jsdom", which gives Testing Library a DOM in Node.

When to use it
  • Component tests that should not depend on a running backend.
  • Error, empty and slow states that are hard to get from a real server. The mock config also takes responseTime and timeout.

Summary

Attach a mock to the request the component uses, render, and assert on the screen. setMock keeps the cache, hooks and callbacks in the test path, and clearMock() plus client.clear() keep tests apart.