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"
placeholder="New password"
defaultValue=""
type="password"
ref={register({
required: "New password is required"
})}
/>
{errors.newPassword && <p>{errors.newPassword.message}</p>}
<label>Confirm new password</label>
<input
name="confirmNewPassword"
placeholder="Confirm new password"
defaultValue=""
type="password"
ref={register({
required: "Confirm new password is required",
validate: value =>
newPassword === value
? true
: "New password and confirm new password does not match"
})}
/>
{errors.confirmNewPassword && (
<p>{errors.confirmNewPassword.message}</p>
)}
<input type="submit" />
</form>
</div>
);
}

--

--