Thanksgiving DealsAmazon USThanksgiving week: Black Friday picks start earlyAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanThanksgiving DealsAmazon USDo not wait for the rush - compare today's dealsAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog

How to Test Zod Validation in React Hook Form (with React Testing Library)

By Freedom251 Team · · 11 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

To test React Hook Form validation with Zod, connect the schema through zodResolver(schema), render the form in a DOM test environment, and exercise it with the same interactions a user performs. Submit invalid data and verify the accessible error and that the submit callback is blocked; correct the value using the form’s configured revalidation event; then submit valid data and verify the callback payload. Await the UI because React Hook Form can update validation state asynchronously.

The approach follows the official React Hook Form testing guidance: test validation, submission, and errors through user-facing interactions rather than by inspecting private form state.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What do you need before writing the tests?

You need a form that uses a Zod schema, a test runner configured with a browser-like DOM, and React Testing Library utilities for rendering and interaction. For a web form, the documented setup uses:

  • @testing-library/react for rendering and screen queries
  • @testing-library/jest-dom for readable DOM assertions such as toBeInTheDocument and toHaveTextContent
  • @testing-library/user-event for typing, blurring, tabbing, and clicking as a user would
  • jest-environment-jsdom (or the equivalent DOM environment for your existing runner)

The React Hook Form example is Jest-based, but the assertions also work with another runner when you replace its mock and configuration syntax. Do not mix runner-specific setup into the form assertions; keep the DOM environment and jest-dom import in the test setup file used by your project.

Popular on Amazon
Sale
Silkland 40Gbps USB C 90 Degree Right Angle Adapter 2 Pack, 240W USB4 | Male to Female Extender, 8K@60Hz, Thunderbolt 4/3, Steam Deck, ROG Ally, MacBook, Switch 2, iPhone 18/17/16/15, Quest 3 VR
  • 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
  • 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
  • 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
  • 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
  • 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.
npm install -D @testing-library/react @testing-library/jest-dom @testing-library/user-event jest-environment-jsdom

Import jest-dom once from the runner’s setup file:

import '@testing-library/jest-dom';

Your test environment must provide document, window, and related browser APIs. If a test fails with an error that those globals do not exist, the runner is using a Node-only environment rather than jsdom (or its equivalent).

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do you connect Zod to React Hook Form?

Pass the schema to zodResolver and provide that resolver in the useForm options. React Hook Form runs the resolver against submitted or revalidated values and maps its result into formState.errors.

import { z } from 'zod';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

const schema = z.object({
  email: z.string().email('Enter a valid email'),
});

type FormValues = z.infer<typeof schema>;

type EmailFormProps = {
  onSubmit: (data: FormValues) => void;
};

export function EmailForm({ onSubmit }: EmailFormProps) {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<FormValues>({
    resolver: zodResolver(schema),
  });

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <label htmlFor='email'>Email</label>
      <input id='email' {...register('email')} />
      {errors.email && <p role='alert'>{errors.email.message}</p>}
      <button type='submit'>Submit</button>
    </form>
  );
}

The label gives the input an accessible name, and role='alert' makes the validation message easy for assistive technology and a test to locate. Your production form may use a different schema, field names, or message; the tests should follow those real constraints rather than this example’s email rule.

How should a rendered validation test be structured?

Start with userEvent.setup(), render the component with a mock submit handler, and query controls by role or label. These queries test the public interface of the form and continue to work when the component’s internal implementation changes.

import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { EmailForm } from './EmailForm';

it('validates and submits an email form', async () => {
  const user = userEvent.setup();
  const onSubmit = vi.fn(); // use the equivalent mock for your runner

  render(<EmailForm onSubmit={onSubmit} />);

  // The invalid-submission assertions go here.
});

If your runner uses a different mock factory, substitute it without changing the interaction pattern. The important parts are the DOM render, semantic queries, awaited user actions, and assertions against what the user can see.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do you test an invalid submission?

Leave the field empty (or enter a value that violates the actual schema), click the visible submit button, wait for the error to appear, and verify that the valid-submit callback was not called.

Also popular on Amazon
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
await user.click(screen.getByRole('button', { name: /submit/i }));

expect(await screen.findByRole('alert')).toHaveTextContent(
  'Enter a valid email'
);
expect(onSubmit).not.toHaveBeenCalled();

findByRole combines a semantic query with an asynchronous wait. It is appropriate when the error is rendered after React Hook Form’s validation update. If your application deliberately uses a different message, assert that configured message or assert the presence of the alert without assuming text that the schema does not guarantee.

For multiple fields, submit once and assert each expected field error by its accessible role, label relationship, or another stable user-facing attribute. Do not reach into React Hook Form’s internal control object to decide whether validation ran; the rendered error and blocked submission are the observable outcomes that matter.

How do you test that an invalid value can be corrected?

First create the error, then enter a value that satisfies the schema and perform the event selected by the form’s revalidation configuration. React Hook Form treats mode and reValidateMode separately: mode controls validation before the first submission, while reValidateMode controls how fields with errors are checked after submission.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If the form uses the default or an explicit onChange revalidation strategy, the error should clear after a valid change:

await user.click(screen.getByRole('button', { name: /submit/i }));
expect(await screen.findByRole('alert')).toBeInTheDocument();

await user.type(
  screen.getByRole('textbox', { name: /email/i }),
  '[email protected]'
);

await waitFor(() => {
  expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});

Do not assume that typing alone is the right trigger. If the form specifies reValidateMode: 'onBlur', type the value and then blur the field, for example with user.tab(). If it specifies submit-time revalidation, click Submit again and assert the resulting state. The interaction in the test should match the form’s real configuration.

When the error remains, check whether the value truly satisfies the schema, whether the input’s registered name matches the schema key, and whether the test waited for the asynchronous update. A message that remains visible can be correct when the new value is still invalid.

How do you test a valid form submission?

Enter values that satisfy every schema constraint, submit through the visible button, and assert that the callback receives the expected object. If the component renders a success message, assert that user-visible result as well.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Also popular on Amazon
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
await user.type(
  screen.getByRole('textbox', { name: /email/i }),
  '[email protected]'
);
await user.click(screen.getByRole('button', { name: /submit/i }));

await waitFor(() => {
  expect(onSubmit).toHaveBeenCalledWith({
    email: '[email protected]',
  });
});

Waiting for the callback is useful even when the schema is synchronous because React Hook Form’s submission and state updates are scheduled through React. If the callback is asynchronous in your application, make the mock return the appropriate promise and await the UI or callback condition that represents completion.

A valid-submission test covers the complete path: the control is registered, the value reaches the resolver, Zod accepts it, React Hook Form calls handleSubmit‘s success branch, and the application receives the parsed data. It therefore complements an invalid-submission test rather than replacing it.

Why do React Hook Form tests need asynchronous assertions?

React Hook Form can perform an asynchronous initial validation pass and can update its error state after an interaction. A test that asserts immediately after render or a click can therefore race the update and produce an act warning or a false negative.

Use one of these patterns:

  • findByRole, findByLabelText, or another findBy* query when the element is expected to appear
  • waitFor when an existing element changes, disappears, or a mock callback must eventually be called
  • an awaited userEvent action for every interaction that can update React state

Do not wrap the initial render in act solely to silence a warning. The documented remedy is to await the resulting UI update. This keeps the test aligned with the way a user observes the form.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should you test the resolver directly as well?

A direct resolver test can be useful when schema-to-error mapping is complex, but it does not replace a rendered form test. The resolver is a plain function: it receives values and returns resolved values or errors, synchronously or asynchronously. A direct test isolates that mapping; a rendered test verifies that the resolver is wired into useForm and that its result is presented correctly.

A resolver unit test follows this conceptual pattern (adapt the third argument and mock syntax to the installed @hookform/resolvers types and runner):

const resolver = zodResolver(schema);

const result = await resolver(
  { email: 'not-an-email' },
  undefined,
  {
    criteriaMode: 'firstError',
    fields: {},
    shouldUseNativeValidation: false,
  }
);

expect(result.errors.email).toBeDefined();

Also test an accepted value and inspect result.values when your schema transforms or normalizes data. Keep this test focused on the schema contract; use the rendered tests for labels, alert placement, validation timing, and submit behavior.

Also popular on Amazon
Sale
BENFEI USB C Hub 5-in-1 with 4K HDMI(Certified), 100W Power Delivery, 3 USB-A, Silicone Cable, Aluminum Case Compatible with MacBook Pro/Air, iPad Pro, iMac, iPhone 15 Pro/Pro Max, XPS, Thinkpad
  • Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
  • Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
  • 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
  • 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
  • Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.

How do validation modes change what the test must do?

The interaction sequence must reflect the form’s actual mode and reValidateMode options. A test that always clicks Submit can miss a form that is intentionally designed to validate on blur or while typing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Configuration Interaction to exercise What to assert
mode: 'onSubmit' Enter an invalid value and click Submit Error appears after submission
mode: 'onBlur' Focus the field, leave it, and await validation Error appears on blur
mode: 'onChange' Type an invalid or valid value Error state changes while editing
mode: 'onTouched' Touch the field, then change it Validation follows the touched-field behavior
reValidateMode: 'onChange' Submit invalid data, then type a valid value Error clears after the change
reValidateMode: 'onBlur' Submit invalid data, correct it, then blur Error clears after blur

The table describes the event your test should drive, not a recommendation to change the form’s UX. Read the options from the component under test and cover the behavior that users will actually encounter. The useForm API documentation defines these timing controls.

What should you query in an accessible way?

Prefer getByRole for buttons, textboxes, and alerts, and getByLabelText when a label is the most stable identifier. A query such as getByRole('textbox', { name: /email/i }) confirms that the field is exposed with the expected accessible name, not merely that an element with a particular CSS class exists.

Give each validation message an association that users can understand. A visible paragraph with role='alert' is one option; an application that uses aria-describedby can assert the description through the field’s accessible behavior instead. Match the assertion to the markup your application intentionally provides.

Avoid broad text searches when several fields can show similar messages, and avoid selectors tied to generated class names. Stable labels, roles, and button names make failures point to a real user-facing regression.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why might the error message not appear?

When an expected error is missing, inspect the wiring and timing in this order:

  1. Registration: confirm the input spreads register('fieldName') and that the name exactly matches the schema key.
  2. Resolver coverage: confirm the component passes resolver: zodResolver(schema) to the same useForm instance used by handleSubmit.
  3. Rendering: confirm the component reads the field from formState.errors and actually renders an element when an error exists.
  4. Trigger: perform the event selected by mode or reValidateMode; typing will not trigger an on-blur-only form.
  5. Awaiting: replace an immediate assertion with findBy* or waitFor when the state update is asynchronous.
  6. Environment: verify that the test runner uses jsdom (or its equivalent) and that jest-dom is loaded before assertions.

The React Hook Form FAQ specifically points to checking field rules or resolver coverage and waiting for asynchronous UI updates. If the alert is present but the text differs, inspect the schema’s configured message rather than weakening the test to an unrelated string.

Also popular on Amazon
𝟒𝐏𝐚𝐜𝐤 𝐔𝐩𝐠𝐫𝐚𝐝𝐞𝐝 USB to USB C Adapter,Type-C Female to A Male Charger Converter for iPhone 18 Charger,iWatch Ultra SE 9 10,iPhone 17 Pro Max 16 15 14,Samsung S25,AirPods,iPad,Car,Xbox
  • 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
  • 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
  • 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
  • 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
  • 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.

How do you handle Zod and resolver version compatibility?

The official getting-started documentation currently notes that Zod v4 support requires @hookform/resolvers ^3.10 or newer paired with Zod ^3.25 or Zod v4. It also calls out TypeScript module resolution settings of bundler, node16, or nodenext for package subpath exports.

These are compatibility guidance, not a substitute for checking your lockfile. If the Zod resolver import fails or types do not resolve, compare the installed versions with the current React Hook Form getting-started documentation, verify the TypeScript moduleResolution setting, and reinstall dependencies consistently. Package compatibility evolves, so do not copy an old version pin without checking the project’s current toolchain.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What belongs in a complete test suite?

For a form with a single required email, the minimum useful suite has three user-visible paths:

  • Invalid submission: submit an empty or malformed value, see the expected error, and confirm the success callback is untouched.
  • Correction: fix the value and trigger the configured revalidation event; confirm the error clears or changes appropriately.
  • Valid submission: enter valid data, submit, and confirm the callback receives the expected data and any success UI appears.

Add field-specific cases for constraints that materially affect behavior, such as a second invalid format, a minimum length, a required checkbox, or a cross-field rule. If the schema transforms input, assert the parsed value received by the callback rather than only the raw string typed into the control. If resolver mapping is unusually complex, add focused direct-resolver tests while retaining at least one rendered test for the integration.

Practical checklist before you commit the tests

  • Is the test running in a DOM environment?
  • Are controls located by accessible role or label?
  • Does the form use the real zodResolver(schema) configuration?
  • Does invalid submission prove both the error and the absence of a valid callback?
  • Does correction use the configured revalidation event?
  • Does valid submission assert the callback’s data shape?
  • Are every user interaction and asynchronous UI assertion awaited?
  • Do error-text assertions reflect the application’s configured Zod messages?
  • Have you checked resolver and Zod versions if imports or TypeScript types fail?

Following this sequence tests the contract a user depends on: invalid values are explained, corrections are recognized at the intended time, and valid values reach the submit handler in the expected form.

Frequently Asked Questions

Can I use fake timers with React Hook Form validation tests?

Avoid enabling fake timers unless the component specifically depends on timers. They can interfere with the asynchronous scheduling used by user-event and React Hook Form; if your runner requires them, configure user-event to cooperate with that runner and keep the validation assertions awaited.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How can I assert a field error without hard-coding its wording?

Query the field or alert by its accessible role and assert that an error element is present. If wording is part of your product requirement, assert the exact configured Zod message; otherwise, keep the test focused on the presence and association of the error.

What if the submit handler throws or returns a rejected promise?

Treat that as a separate submission-path test. Make the mock rejection explicit, await the UI state your component promises to show, and assert the error-handling behavior rather than treating a rejected handler as a validation failure.

Does a Zod transform change what the submit assertion should contain?

Yes. React Hook Form receives the resolver’s parsed result, so a transform can make the callback value differ from the literal text entered. Assert the data contract your application consumes, and use a direct resolver test when the transformation rules deserve isolated coverage.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply. Prices as of November 22, 2026 6:44 pm GMT+0530.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.