Basic Component Testing with React Testing and TypeScript

In this article, we will create a simple React component and do some basic testing on the component using React Testing. This will help you get acquainted with the React Testing library and how to write tests.

Installation

The React Testing library comes by default when you run create-react-app, so it should already be in your project if you created your React project with that command.

Create TypeScript component

First, we will create a component using TypeScript. Make a file called Container.tsx

In the Container component, we will have a div element with a h1 inside of it:

import React from "react";

export const Container = ({ title }: { title: string }) => (
  <div role="contentinfo">
    <h1>{title}</h1>
  </div>
);

We define a title prop with a type of string in TypeScript with the code: { title }: { title: string }

We also set an aria-role for the div element of type contentinfo

Write Tests

Now, let’s write some tests for this component

Create a test file called Container.test.tsx

First, we need to add some imports:

import React from "react";
import { render, screen } from "@testing-library/react";
import { Container } from "./Container";

As you can see, we are importing render and screen from the React testing library, which we will use momentarily.

To create a new test, we use the following structure (which is based on Jest, which is the underlying test framework):

test("Name of test", () => {
   // Function body of test
});

So, we will create a test named “renders title” and then define it:

test("renders title, () => {
    // Test will go here
})

First, render the Container component:

render(<Container title={"New Container"} />);

Next, get access to an element:

const titleElement = screen.getByText(/New Container/i);

There are many ways to get access to an element in the library

  • getByText
  • getByRole (aria-role)
  • getByLabelText
  • getByPlaceholderText

Make an assertion about the element:

expect(titleElement).toBeInDocument()

The above assertion is simply that the title element is in the Container component. This is just a very simple test.

So, here is the full test code:

test("renders title, () => {
    render(<Container title={"New Container"} />);
    const titleElement = screen.getByText(/New Container/i);
    expect(titleElement).toBeInDocument()
})

Run yarn test

The test output should look like this if it passed successfully:

Now, you have a basic introduction to testing components in React.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s