Getting Started with React Testing Library: Writing Your First Test.
Tags: javascript, testing, react, tutorial
Published: 2024-02-23 16:49:49

The difference between Jest and the React Testing Library is important to understand when writing unit tests for React components.

####Jest:

- Jest is a JavaScript testing framework.
- It serves as a test runner, assertion library, and mock/stub/spy library.
- Jest provides a testing environment where you can write and execute your test cases.
- It provides features such as test suites, test cases, mocking functions, code coverage analysis and more.
- Jest is highly optimised for performance and parallelization, making it a popular choice for testing JavaScript applications.

####React Testing Library:

- It's a utility library for testing React components.
- It provides tools for interacting with React components in tests, simulating user behaviour, and asserting on rendered output.
- It encourages testing components in a way that resembles how they will be used by end users.
- It encourages writing tests that focus on behaviour rather than implementation details, resulting in more robust and maintainable tests.
- The React Testing Library works on top of testing frameworks such as Jest, making it easy to integrate with existing Jest test suites.

#### Test's Anatomy.
Overall, the test facility is fundamental to writing tests in Jest. It allows you to organise your test cases, specify the behaviour you want to test, and define the expected results.

`test(name, fn, timeout)`

where: 
`name` is a descriptive string that clearly indicates what aspect of the code is being tested. 
`fn` is the function containing the actual test code.
`timeout` is the maximum amount of time (in milliseconds) that Jest will allow the test case to run before considering it a failure. The default timeout is 5000 milliseconds (5 seconds), but you can change it to suit your tests.

 RTL unit tests consist of 3 stages: 
- render the component
- find the element rendered by the component
- assert against the element found in step 2, which passes or fails the test.


#### RTL Queries.

So how can we find element? 

RTL provides a variety of query methods to find elements on the page when writing tests. Here's a breakdown of the three types of queries you mentioned:

**getBy & getAllBy**

**`getBy`** is used to find a single element that matches the specified criteria. If no matching element is found, it throws an error.
**`getAllBy`** is used to find multiple elements that match the specified criteria. If no matching elements are found, it throws an error.

**queryBy & queryAllBy**

**`queryBy`** is similar to getBy, but it returns null if no matching element is found instead of throwing an error.
**`queryAllBy`** is similar to getAllBy, but it returns an empty array if no matching elements are found instead of throwing an error.

**findBy & findAllBy**

**`findBy `** is used to find a single element asynchronously. It waits for the specified element to appear in the DOM within a certain timeout period. It returns a Promise that resolves when the element is found or rejects if the element is not found within the timeout.
**`findAllBy`** is similar to findBy, but it finds multiple elements asynchronously. Like findBy, it returns a Promise that resolves to an array of elements when they are found or rejects if no elements are found within the timeout.


####How to start writing unit tests? 
If setup Jest/ React Testing Library is already done 
if not please read my article [Getting start with React Testing Library](https://dev.to/jagodabieniek/testing-react-components-with-jest-and-react-testing-library-e6i) we can move on to writing our first unit test.

Let's see what to test. In our case it will be simple component: 

_HomeView.tsx_
```
const HomeView = () => <h1>Hello home view</h1>;
export default HomeView;

```
Our example component displays the string 'Hello home view', so the test case should check whether the string 'Hello home view' is displayed correctly. 

Create a test file. There are actually 3 ways to do this: 

- inside component folder => ./HomeView/HomeView.test.tsx
- inside component folder => ./HomeView/HomeView.spec.tsx
- inside create src/_tests_ ./HomeView.test.tsx 

It is recommended that you always place your tests next to the code they test, so that relative imports are shorter. 

In this tutorial I have chosen the first option.  

Inside HomeView.test.tsx. Let's import the necessary dependencies 

```
import { render } from '@testing-library/react';
import HomeView from './HomeView';

```
As you can see, we first import the _render_ function, which allows us to render React components in a test environment, and the function takes a JSX element <HomeView />. Then we can use the utilities mentioned above.  

```
import { render } from '@testing-library/react';
import HomeView from './HomeView';


 test('HomeView renders the heading with correct text', ()=>{
   // render compoment 
   render(<HomeView/>); 
   // heading element 
   const headingElement = 
     screen.getByRole('heading', { level: 1}); 
   // assertion 
   expect(headingElement).toBeInTheDocument();
  })

```