DEV Community

Cover image for React Testing For Beginners
Safak
Safak

Posted on

React Testing For Beginners

Today, we are going to talk about one of the most underrated parts of development: Testing. We all know testing is really important and a properly tested software product ensures dependability, security, and high performance, which leads to time savings, cost effectiveness, and customer satisfaction. But why do we underestimate testing even though it's not that challenging?

"Because it's boring!"

It's true. Nobody wants to be a goalkeeper instead of dancing with the ball on the field as other players do. However, you need to be aware of how much time you can waste with a faulty project. You think you've completed the product, but it comes back to you again and again. You have to check components, you have to find where the problem is. And without testing, you'll never know if it's working properly. If that sounds overwhelming enough, let's get started and see how we can test our React applications.

For a better understanding, you can watch the video version of the tutorial. It'll be more useful for beginners. Here it is:

Reading is better? Let's continue.

Firstly we need a testing library to reach DOM elements and interact with them, and need a testing framework that we can compare the test result with the real result. In this tutorial, we'll use @testing-library/react and jest. If you are using create-react-app, you don't have to install anything, the app already includes them. If you don't use create-react-app, you should run the following line.

npm install --save-dev @testing-library/react jest

Let's try to understand, how it works. To do that, we'll add some HTML elements in App.js.

function App() {

  const a = 2
  const b = 4

  return (
    <div className="app">      
      <ul>
        <li>Apple</li>
        <li>Banana</li>
        <li>Orange</li>
      </ul>

      <h1 data-testid= "title">Hello</h1>
      <span title="sum">{a+b}</span>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Our goal is testing:

  • whether the fruit list includes 3 items,
  • whether the h1 tag exists,
  • whether the span tag contains the sum of variables a and b.

Let's open App.test.js file and start out tests.

Test 1

  • The first thing we need to do is create a new test and giving a description.
test('should render 3 list items', () => {

});
Enter fullscreen mode Exit fullscreen mode
  • Okey. We've described our goal. And now, we should reach DOM elements to select list items. To do that we are going to use render method of React testing library, and render our component.
import { render } from '@testing-library/react';
import App from './App';

test('should render 3 list items', () => {
  render(<App />);
});
Enter fullscreen mode Exit fullscreen mode
import { render, screen } from '@testing-library/react';
import App from './App';

test('should render 3 list items', () => {
  render(<App />);
  const listitems = screen.getAllByRole("listitem");
});
Enter fullscreen mode Exit fullscreen mode

** Since we have more than one listitem, we don't use getBy, we use getAllBy.

** screen object represents the entire HTML document in the rendered component.

  • Finally, we can compare the result using Jest. To to that, we'll write our expectation.
import { render, screen } from '@testing-library/react';
import App from './App';

test('should render 3 list items', () => {
  render(<App />);
  const listitems = screen.getAllByRole("listitem");
  expect(listitems).toHaveLength(3);
});
Enter fullscreen mode Exit fullscreen mode

** When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things. To see all expect methods, you can check here.

And. That's all. Let's check the test result.

npm run test

And as you realize, the test passes. Congratulations. Now you can change the list item number and see how it fails.

Test 2

In this test, we are going to check whether the h1 tag exists or not. And to select h1 item we'll use another query.

<h1 data-testid= "title">Hello</h1>

This time we are using a test id to identify h1 tag. Let's use it and select the item and check for its existence.

import { render, screen } from '@testing-library/react';
import App from './App';

test('title should be rendered', () => {
  render(<App />);
  const title = screen.getByTestId("title");
  expect(title).toBeInTheDocument();
});
Enter fullscreen mode Exit fullscreen mode

It's that easy.

Test 3

In the last test we are going to check the sum of variables.
a = 2
b = 4
And we are expecting 6. Let me show you another testing library query.

<span title="sum">{a+b}</span>

As you can see, we are using another identifier which is title. Let's use it and select the item and check the total number.

import { render, screen } from '@testing-library/react';
import App from './App';

test('sum should be 6', () => {
  render(<App />);
  const sum = screen.getByTitle("sum");
  expect(sum.textContent).toBe("6")
});
Enter fullscreen mode Exit fullscreen mode

And now, we have 3 successful tests. Of course you can use other expect methods. It's really flexible. Let's try another method.

import { render, screen } from '@testing-library/react';
import App from './App';

test('sum should be 6', () => {
  render(<App />);
  const sum = screen.getByTitle("sum");
  expect(sum).toHaveTextContent("6")
});
Enter fullscreen mode Exit fullscreen mode

It'll give us the same result. You can also try another alternatives in Jest documentation.

Now, you are able to create other basic tests on your own :) If you want to learn more advanced concepts and see how to test a real world example you should definitely check my React testing crash course video.

I hope it was useful. Thanks for reading :)

My other posts
🔥 Lama Dev YouTube Channel
⚡️ Lama Dev Facebook

Discussion (3)

Collapse
carlosbarlv profile image
carlosbarlv

Thank you for posting :)

Collapse
alirazashaheb profile image
ALI RAZA SHAHEB

❤ Thank You so much for posting. Please keep posting such valuable content

Collapse
vitaliykreminskiy profile image
Vitaliy Kreminskiy

Now, do this with React Native