Testing react component that uses react-hook-form

Bhargav Thakrar
3 min readApr 26, 2020

React hook form is one of the most poplar library used to create forms in react components. It drastically reduces the amount of code that one has to write for creating forms and writing validations.

You would find ample amount articles and blogs all over the internet on how to use this library. Their own documentation is also well written and easy to follow and understand. But, this post is about testing the component that uses react hook form.

Coming straight to the point, consider a basic form to reset your password. It’s a simple form with two fields — New password and Confirm new password. With the basic usage of react hook form, we are using one more function from the library i.e. watch. It basically watches the new password field and its value is compared with confirm new password field so that we have a validation in place that ensures both the password field values are exactly same.

import React from "react";
import { useForm } from "react-hook-form";
import apiCall from './lib/apiCall';
export default function ResetPassword() {
const { register, errors, handleSubmit, watch } = useForm();
const newPassword = watch("newPassword");
const onSubmit = async data => {
await apiCall(data);
};
return (
<div>
<h1>Reset password example</h1>
<form onSubmit={handleSubmit(onSubmit)}>
<label>New password</label>
<input
name="newPassword"…

--

--