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 />);
expect(getByLabelText('Username')).toBeInTheDocument();
expect(getByLabelText('Password')).toBeInTheDocument();
expect(getByText('Login')).toBeInTheDocument();
});
// Well, now we got these covered, I guess!!
// Now, let's verify the main functionality of a login form, when the form
// is submitted it calls the prop with the correct username and password.
it('should call the onLogin prop with the username and password when the form is submitted', () => {
const onLogin = jest.fn();
const { getByLabelText, getByText } = render(<LoginForm onLogin={onLogin} />);
const usernameInput = getByLabelText('Username');
const passwordInput = getByLabelText('Password');
const loginButton = getByText('Login');
fireEvent.change(usernameInput, { target: { value: 'testuser' } });
fireEvent.change(passwordInput, { target: { value: 'testpassword' } });
fireEvent.click(loginButton);

--

--

Shuvo Habib

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