React Testing Library: How does it look like writing Unit Tests in 2023?

Shuvo Habib
6 min readJan 27, 2023
Don’t be alone in the Dark, write unit tests!

Hi this is Habib, just another Lead Frontend Engineer at Deriv, a fintech company. I am here to get you introduced with writing unit tests, if you have not written in 2022, get it started by earlier 2023 for your React Components..

Today we will write a test for a React component LoginForm. When you hear it, what comes to your mind?

  • A login form with,
    - a username field
    - a password field
    - and a Login button

Fare enough, let’s list out what we need and create tests for it.

  1. The first test should verify that the component renders a form with a username input, a password input, and a login button.
  2. The second test should verify that when the form is submitted, the component calls the onLogin prop with the correct username and password.
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import LoginForm from './LoginForm';
describe('LoginForm', () => {
// Let's make sure we have the input fields as promised!
it('should render a form with a username and password input and a login button', () => {
const { getByLabelText, getByText } = render(<LoginForm />);

--

--

Shuvo Habib

I'm a storyteller about UX, Frontend dev technologies, and A/B testing