Sub topic 18
Testing forms with Testing Library
This chapter assumes you can write a React Hook Form and Zod form like the sign-up form from earlier chapters. It also assumes you know basic Vitest or Jest syntax (describe, it, expect) and async/await. The examples use Vitest, Testing Library, and user-event. Jest works the same way apart from the vi helpers, which become jest.
What to test and what to leave alone
React Hook Form and Zod already have their own test suites. Your tests should check behavior a user can see:
- Which error messages appear for which input.
- Whether the submit handler runs, and with what data.
- What the form shows when the server rejects the submission.
Do not assert on internal state such as formState, on how many times a component rendered, or on which resolver you configured. Those details break when you refactor, even if the form still works.
Zod rules themselves are plain functions, so you can test them without React. Test the schema directly when a rule is complex. Test through the rendered form when you want to confirm that the messages reach the right place on screen.
Setting up the test environment
Install the libraries and tell Vitest to use a browser-like DOM.
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom// vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
environment: "jsdom",
setupFiles: ["./src/test-setup.ts"],
},
});// src/test-setup.ts
import "@testing-library/jest-dom/vitest";The setup file adds matchers such as toBeInTheDocument and toBeDisabled. Testing Library cleans up rendered components after each test automatically when your test runner exposes global afterEach. If you keep Vitest's default of no globals, set globals: true in the config, or call cleanup yourself.
How a form test flows
A form test follows the same path a user does. Validation in React Hook Form is asynchronous, so errors do not appear in the same tick as the click. That is why the examples use findBy queries and waitFor.
Choosing queries
Testing Library offers three families of queries. Pick by what you expect to be true at that moment.
| Query | Returns | When no match | Use it for |
|---|---|---|---|
| `getBy...` | The element | Throws | Elements that must exist right now |
| `queryBy...` | The element or `null` | Returns `null` | Asserting that something is absent |
| `findBy...` | A promise of the element | Rejects after a timeout | Elements that appear after validation or a request |
Prefer queries that mirror how users and assistive technology find things: getByLabelText for inputs, getByRole("button", { name }) for buttons, and getByRole("alert") for error messages. This is one more reason to keep the label and htmlFor pairs and the role="alert" messages from the earlier chapters. If a test cannot find an input by its label, a screen reader user probably cannot either.
Testing the sign-up form
The tests below use the SignUpForm from earlier in this tutorial. They assume its onSubmit also includes the 409 handling with setError from the server errors chapter, and that the component is exported from ./SignUpForm.
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, describe, expect, it, vi } from "vitest";
import { SignUpForm } from "./SignUpForm";
function mockFetch(status: number) {
const fetchMock = vi.fn().mockResolvedValue({ ok: status < 400, status });
vi.stubGlobal("fetch", fetchMock);
return fetchMock;
}
async function fillAndSubmit(email: string, password: string) {
const user = userEvent.setup();
if (email) await user.type(screen.getByLabelText("Email"), email);
if (password) await user.type(screen.getByLabelText("Password"), password);
await user.click(screen.getByRole("button", { name: "Create account" }));
}
describe("SignUpForm", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("shows required errors and does not submit an empty form", async () => {
const fetchMock = mockFetch(201);
render(<SignUpForm />);
await fillAndSubmit("", "");
expect(await screen.findByText("Email is required")).toBeInTheDocument();
expect(screen.getByText("Use at least 8 characters")).toBeInTheDocument();
expect(fetchMock).not.toHaveBeenCalled();
});
it("rejects a malformed email", async () => {
const fetchMock = mockFetch(201);
render(<SignUpForm />);
await fillAndSubmit("not-an-email", "longenough1");
expect(await screen.findByText("Enter a valid email")).toBeInTheDocument();
expect(fetchMock).not.toHaveBeenCalled();
});
it("posts the typed values when the data is valid", async () => {
const fetchMock = mockFetch(201);
render(<SignUpForm />);
await fillAndSubmit("[email protected]", "longenough1");
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe("/api/sign-up");
expect(JSON.parse(init.body)).toEqual({
email: "[email protected]",
password: "longenough1",
});
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("shows a server error on the email field", async () => {
mockFetch(409);
render(<SignUpForm />);
await fillAndSubmit("[email protected]", "longenough1");
expect(
await screen.findByText("This email is already registered"),
).toBeInTheDocument();
});
});Each test follows the same steps: arrange a fetch response, render, act as a user, then assert on what the user would see. The fillAndSubmit helper keeps the tests short without hiding what happens.
Notice the order of the assertions in the first test. findByText waits for the first error, which means validation has finished. After that, the synchronous getByText for the second error is safe, because the resolver reports all field errors in one pass.
Testing the schema without React
For rules with several branches, test the schema directly. These tests are fast and need no DOM. This example assumes passwordSchema from the cross-field chapter is exported from ./passwordSchema.
import { describe, expect, it } from "vitest";
import { passwordSchema } from "./passwordSchema";
describe("passwordSchema", () => {
it("accepts matching passwords", () => {
const result = passwordSchema.safeParse({
password: "longenough1",
confirmPassword: "longenough1",
});
expect(result.success).toBe(true);
});
it("reports a mismatch on confirmPassword", () => {
const result = passwordSchema.safeParse({
password: "longenough1",
confirmPassword: "different1",
});
expect(result.success).toBe(false);
if (!result.success) {
expect(result.error.issues[0].path).toEqual(["confirmPassword"]);
expect(result.error.issues[0].message).toBe("Passwords do not match");
}
});
});Checking path is the important part. If the path option were missing from refine, the error would attach to the form root and the field-level message would never show. A schema test catches that cheaply, and a component test confirms the message appears next to the right input.
Common errors
- Using
getByfor an error that appears later. The query runs before validation finishes and throws. Useawait findBy...orwaitFor. - Using
fireEvent.changeandfireEvent.click. These dispatch single events and skip the focus, keydown, and blur sequence that real typing produces. That matters formode: "onBlur". UseuserEvent, and callawait user.tab()to trigger a blur. - Asserting on submit before the promise resolves.
handleSubmitis async. Wrap the assertion on a mock inwaitFor. - Leaking mocks between tests. A stubbed global
fetchstays in place until you remove it. Callvi.unstubAllGlobals()inafterEach, or you may get passing tests that depend on order. - Testing transforms through the DOM only. For the
quantityform that transforms a string to a number, assert the type of the value your submit callback receives, as intypeof values.quantity. The input element always shows a string.
Exercise
A test clicks submit on an empty form, then runs expect(screen.getByText("Email is required")).toBeInTheDocument() and fails with "Unable to find an element". The form works in the browser. What is wrong, and how do you fix it?
Show answer
The resolver validates asynchronously, so the error has not rendered when getByText runs, and getBy throws immediately. Use expect(await screen.findByText("Email is required")).toBeInTheDocument(), which waits for the message to appear. Also confirm the click was awaited, since user.click returns a promise.
Exercise
Write the assertion that checks no request was sent when the password is too short, given a fetchMock created with vi.fn(). Why must it come after an awaited findByText for the error?
Show answer
expect(fetchMock).not.toHaveBeenCalled(). If you assert right after the click, validation may not have finished, so the check can pass only because the submit handler has not had time to run. Waiting for the error message first proves the resolver rejected the values, which makes the absence of a fetch call meaningful.