DEV Community

TulusIbrahim
TulusIbrahim

Posted on • Edited on

How to Test React Component Using Jest

In this tutorial, we will learn how to do unit testing to a react component using Jest. Jest is a testing framework that works with react, node, vue, and other tools with focus on simplicity. Unit test aim to make sure that one component is behave as expected despite many variations of props passed to it. The expectation here could be come from the design system.

Some of the benefit of unit testing are:
Make sure the code, design, implementation is behave as expected.
Give the developer confident when about to do some refactoring, knowing that they have safety net about the component code.
For the record I will use nextjs in this tutorial. Follow the installation guide on nextjs docs about jest here. After the step is done, now we are good to go.

Ok let’s get to the code

Let’s start by creating a test file with .test.ts(.test.js if you use js) extension. Where to place the file is about your preference, but there are convention to place it within the tests folder in the root folder or next to the component itself. So for example if you have button/index.tsx, then the test file would be in the button/index.test.ts, right next to the component file.

Ok let’s start importing some stuff to begin with

Image description

We import import ‘@testing-library/jest-dom’; so we can get access to test the DOM state, and some essential utilities from @testing-library/react to test the component.

Image description

This is what a single test block look like. First give the test a clear name so we can undertand it better. You can render any component within the render method, in this case we want to render the button with a text within it. Render method return various function to assert the DOM state, but there we are destructuring the getByText function. Within the getByText function, you can use a string to find a text or a regex expression as well.

Image description

Another example is when we want to test the interaction with the component, we want to check if the onClick function actually called when we tapped on the button, we could create a mock function by writing let fn = jest.fn(); then pass it as a function to onClick props. Render the component, after it rendered, we fire an event by calling fireEvent.click. To target which DOM to click, we need to find it by findByText. Then we can expect the mock function fn is have been called.

If we run yarn test in the terminal, we can see the result as below.

Image description

Top comments (0)