Unit Testing In React: Introduction

Last updated on December 28, 2022

Unit testing is an important part of the Software development life cycle and unit tests are written and executed by developers in which the smallest testable units of the code are tested to check whether the individual functionality is working as intended. The main aim of unit testing is to find bugs in the isolated functionality and improve the quality of code.

ReactJS is the popular JavaScript library for building complex user interfaces encapsulating the functionality into reusable, isolated, and independent smaller components.

We will be using Jest, a JavaScript test runner which will execute all our unit tests, and React-testing-library to write the actual unit tests where we will be checking the behavior of our component (rather than the implementation details of the code) as supposed the way end user will be interacting with.

Now let’s start the writing unit tests.

Step 1

Create a new react app using the below command

npx create-react-app unit-test-demo

open package.json and you can ensure that both jest and react-testing-library will be installed by default so nothing needs to be installed manually.

Step 2

Create a simple component named UserData which accepts value through props and just displays that on the screen. So testing this is fairly easy and there will be only 2 scenarios to check when the userName is passed and when not.

import { React } from "react";

const UserData = ({ userName }) => {
  return (
    <div data-testid="username">
        {userName?userName:'Anonymous'}
    </div>
  );
};
export default UserData;

Note: I have provided data-testid an attribute to the div using which we can easily find our element using getByTestIdand There are other ways to select the elements also eg ByRole, ByText, ByTagName…

Step 3

Now create the file naming UserData.test.jsx which will help jest to identify and run the test file.

What is the basic structure of testing code block? Let’s understand that first

  • Create the test block which contains the descriptions and callback function where our test case resides. you can wrap multiple test blocks into a single test suite also although that’s completely optional.
  • render the component which you want to test
  • Now select the elements and interact with those elements like clicking, changing the input values, etc…
  • Next, you need to assert the values you might have changed or expected to validate your test cases.
import React from "react";
import UserData from "../UserData";
import { render } from "@testing-library/react";

describe("User Data", () => {
  it("should render with default props", () => {
    const { getByTestId } = render(<UserData />);
    const element = getByTestId("username");
    expect(element.textContent).toMatch("Anonymous")
  });
  it("should render with props provided", () => {
    const userName="Ellie Smith"
    const { getByTestId } = render(<UserData userName={userName}/>);
    const element = getByTestId("username");
    expect(element.textContent).toMatch(userName)
  });
});

I have created 2 test cases for the above component one with the default state and another with the value passed through props and finally expecting the values using the assertion statement.

Step 4

Now the last step is to run the unit test to validate your test cases using the command npm run test and this is how the result will look if all test cases passed.

 PASS  src/components/tests/UserData.test.jsx
  User Data
    ✓ should render with default props (5 ms)
    ✓ should render with props provided (2 ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.312 s, estimated 1 s

Writing test cases for the pure function is fairly simple. Pure function means the functions if provided the same input always returns the same output but in reality, the code logic is much more complex which might involve performing side effects using react hooks and managing the state logic.

So In this article, I have tried to cover the basics of unit testing and how to write and execute the tests with examples. Please provide your valuable constructive feedback/suggestion as it will help in improving and sharing more knowledge with others.

I have planned the next few articles covering the complex and advanced test cases involving react and Redux and uncovering the secret of 100% code coverage, How??.

You can find all code changes related to this series on my GitHub https://github.com/bhuvnesh9758/unit-test-demo

I will be uploading the next article in this series soon. See you soon!!

manorinfinity Written by:

Complex Problem Solver, Outloud Thinker, An Outstanding Writer, and a very curious human being

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.