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.
Opens the example in StackBlitz in a new tab. The first start installs packages and takes a few seconds.
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",
});
npx tiged BetterTyped/hyper-fetch/examples/react/testing hyper-fetch-react-testing && cd hyper-fetch-react-testing && npm install && npm run devsetMockanswers a request in tests. Cache, hooks and callbacks run the same way as with a real response.- Error and edge states: a mock that returns
errorand a status tests the error message without a failing server. - Checking what was sent: the mock receives the request, so a test can assert the payload.
- Isolation:
clearMock()andclient.clear()after each test, so no test sees another test's data.
How it works
-
TodoList.tsxis an ordinary component:useFetch(getTodosRequest)loads the list anduseSubmit(updateTodoRequest)saves a checkbox. It knows nothing about tests. -
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.
-
A failure is a mock with
errorand a status.submit()andsend()resolve with the failed response, they do not throw, so the component shows its error message and the test reads it. -
The save test reads
request.payloadinside the mock and checks that the component sent{ completed: true }. -
afterEachcallscleanup(), removes the mocks withclearMock()and resets the cache and queues withclient.clear(). -
api.tsexports the request with its query params already set, and the component uses that exact object.setMockchanges only the instance it is called on. A request derived earlier withsetQueryParams()orsetParams()keeps its own copy and would still go to the network. Requests derived later, such as the onesubmit({ 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.
- 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
responseTimeandtimeout.
Related
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.
