DEV Community

Kazutora Hattori
Kazutora Hattori

Posted on

Cause and solution for the "Unable to find an element with the text" error in React Hook Form + Chakra UI

Introduction

When I was creating a required input form using React Hook Form and Chakra UI,
I ran into an issue where the error message displayed correctly in the UI, but not in the Jest test.
In this article, I'll share the cause and solution.

Problem

When testing required fields with React Hook Form + Chakra UI,
the error message displayed correctly in production, but the Jest test failed.

Unable to find an element with the text: ID is required
Enter fullscreen mode Exit fullscreen mode

The element was displayed correctly in the UI, but not in the test.
The reason was that React Hook Form validation errors were not immediately reflected in the DOM.
As a result, when I searched for the element with getByText, it wasn't yet in the DOM, causing the test to fail.

Solution

I used findByText from the Testing Library to wait until the element was found.

This fails.

expect(screen.getByText("ID is required")).toBeInTheDocument();
Enter fullscreen mode Exit fullscreen mode

Succeeds with asynchronous support.

expect(await screen.findByText("ID is required")).toBeInTheDocument();
Enter fullscreen mode Exit fullscreen mode

This resolves the discrepancy where the test fails but the UI shows it.

Summary

  • When the UI and Jest behavior differ, suspect asynchronous behavior.

Top comments (0)