Sub topic 18
Testing forms with Testing Library
This chapter tests the SignUpForm from earlier in the tutorial. It assumes you know Vitest (or Jest) basics, can read async/await, and have the SignUpForm component from the earlier chapters.
Test behavior, not internals
React Hook Form keeps values in refs, so there is no state for a test to read. This works in your favor. A good form test does what a user does: type into labelled fields, click submit, and check what appears on screen or what request goes out.
Testing Library encourages this by finding elements through labels and roles. Your htmlFor labels and role="alert" messages therefore serve accessibility and testing together.
Setup
Install the packages and enable jest-dom matchers.
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-domSet environment: "jsdom" in your Vitest config. Each test file below imports @testing-library/jest-dom/vitest directly, so no extra setup file is needed.
Testing validation and submission
Use userEvent, not fireEvent. It fires the full sequence of events a browser would, including focus, key presses and blur. Validation and submission are asynchronous, so use findBy queries or waitFor for anything that appears after a submit.
import "@testing-library/jest-dom/vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SignUpForm } from "./SignUpForm";
describe("SignUpForm", () => {
const fetchMock = vi.fn();
beforeEach(() => {
fetchMock.mockReset();
fetchMock.mockResolvedValue({ status: 201 });
vi.stubGlobal("fetch", fetchMock);
});
afterEach(() => {
vi.unstubAllGlobals();
});
it("shows schema errors and does not call the API", async () => {
const user = userEvent.setup();
render(<SignUpForm />);
await user.click(screen.getByRole("button", { name: "Create account" }));
expect(await screen.findByText("Email is required")).toBeInTheDocument();
expect(screen.getByText("Use at least 8 characters")).toBeInTheDocument();
expect(fetchMock).not.toHaveBeenCalled();
});
it("submits valid values", async () => {
const user = userEvent.setup();
render(<SignUpForm />);
await user.type(screen.getByLabelText("Email"), "[email protected]");
await user.type(screen.getByLabelText("Password"), "correct-horse");
await user.click(screen.getByRole("button", { name: "Create account" }));
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
expect(fetchMock).toHaveBeenCalledWith(
"/api/sign-up",
expect.objectContaining({
method: "POST",
body: JSON.stringify({
email: "[email protected]",
password: "correct-horse",
}),
})
);
});
});The first test proves that zodResolver blocks submission. The second proves that handleSubmit passes the parsed values to your handler.
Testing server errors
If your onSubmit uses the setError pattern from the server errors chapter, make the mocked response return status 409 and assert on the message. Add this test inside the same describe block.
it("shows a server error on the email field", async () => {
fetchMock.mockResolvedValue({ status: 409 });
const user = userEvent.setup();
render(<SignUpForm />);
await user.type(screen.getByLabelText("Email"), "[email protected]");
await user.type(screen.getByLabelText("Password"), "correct-horse");
await user.click(screen.getByRole("button", { name: "Create account" }));
expect(
await screen.findByText("This email is already registered")
).toBeInTheDocument();
});Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `getByText` right after a click | Fails because validation has not finished | Use `findByText` or `waitFor` |
| Not awaiting `user.click` or `user.type` | Assertions run too early | Always `await` user-event calls |
| Querying by `id` or `name` | Tests break on markup changes | Query by label or role |
| Letting the real `fetch` run | Network errors or flaky tests | Stub `fetch` or use a mock server |
Exercise
A test types a valid email, leaves the password empty, clicks submit, and then runs expect(screen.getByText("Use at least 8 characters")).toBeInTheDocument(). It fails intermittently. What is the likely cause and the fix?
Show answer
The resolver validates asynchronously, so the error message may not be rendered yet when the synchronous getByText runs. Replace it with await screen.findByText("Use at least 8 characters"), and make sure the click is awaited.