Search⌘ K
AI Features

Testing Custom Hooks with State

Explore how to write tests for React custom hooks that manage state, such as useForm. Learn to use renderHook and wrap state-changing actions in act to verify initial values, field updates, and form submissions within your tests.

Starter project

The project for this lesson contains a custom hook called useForm. This hook tracks the value of a field in a form and can handle the initial part of the form submission. It is a very simplified version of useForm from React Hook Form.

In this lesson, we’ll create tests on useForm.

A copy of the project is in the code widget below. Clicking the “Run” button executes the tests.

export default "test-file-stub";
Starter project

Testing the initial render

The project contains an empty test in useForm.test.js. We’ll implement this test to verify that the values object returned from useForm is initially empty.

Use renderHook as follows to render useForm in a test component:

 ...