Testing-Reactjs-Apps-with-React-Testing-Library-and-Jest-A-complete-guide

Testing Reactjs Apps with React-Testing-Library and Jest: A complete guide

Testing Reactjs apps is the process of automating assertions between the code’s output and what we expect.
Our assertions about testing React JS apps are evaluated by how the app renders and responds to user engagement.
There are numerous testing paradigms and philosophies to choose from. The purpose of this article is to discuss how to write unit and component tests (or integration tests)

What is Testing?

Testing is the process of automating assertions between the code’s output and what we expect. Our assertions about testing React JS apps are evaluated by how the app renders and responds to user engagement. There are numerous testing paradigms and philosophies to choose from. The purpose of this article is to discuss how to write unit and component tests (or integration tests).

Why Testing?

Before we do something, it’s crucial to know why we’re doing it. So, why would we test, and what is the point of it?

The primary goal of testing is to avoid regression. The recurrence of a previously corrected bug is known as regression. It causes a feature to stop working as it should after a specific event happens.

Complex components and modular applications are tested to assure their functionality.

Testing is necessary for a software application’s or product’s effective performance.

Testing improves the sturdiness and error resistance of software. It’s a technique to make that your code is doing what you want it to and that your app is functioning properly for your consumers.

What is JEST?

Jest is a JavaScript testing framework that interacts well with React and allows developers to run tests on JavaScript and TypeScript code.

It’s a framework that focuses on simplicity while also providing a robust and beautiful API for creating isolated tests, snapshot comparison, mocking, test coverage, and more.

Jest may also be used to validate nearly anything involving JavaScript, particularly the rendering of web applications in the browser. Jest is also a popular choice for automated browser testing, making it one of the most extensively used Javascript testing frameworks.

Hire React js Developers

What is React-Testing-Library?

The React Testing Library is a JavaScript testing tool designed to test React components. It tests the UI’s behavior by simulating user interactions on isolated components and asserting their outcomes. React-testing-library comes inbuilt while you create yours react app.

React-Testing-Library Vs JEST

The React Testing Library is not a substitution for Jest. Each has a different feature, and you’ll need both to test your components.

Jest is a test runner that finds and runs tests before determining whether they passed or failed. Jest also includes features for test suites, test cases, and assertions.

Virtual DOMs are provided by the React Testing Library for testing React components.

When we run tests outside of a web browser, we need a virtual DOM to render the app, interact with the elements, and see if the virtual DOM performs correctly (like changing the width of a div on a button click)

Testing Reactjs apps

Let’s Understand with an example:

import React from 'react';
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import MyInfoScreen from './MyInfoScreen';
import { getMyInfoMetadata } from '../../actions/selfservice/MyInfoActions';

// Mock store using JEST
jest.mock('../../Store.js')


// Mock Actions
jest.mock('../../actions/selfservice/MyInfoActions', () => ({
getMyInfoMetadata: jest.fn(),
}))

describe('MyInfoScreen', () => {
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

beforeEach(() => {
jest.useFakeTimers();
});

afterEach(() => {
jest.clearAllTimers();
});

const store = mockStore({
uiMetadata: {
currentUser: {
id: 'test'
},
oauthClientId: 'testId',
titleOrganizationName: 'test title'
}
});


it('should render WidgetPageContainer component', async () => {
// mocking API call using mockImplementation by JEST
getMyInfoMetadata.mockImplementation(() => Promise.resolve({}));

render(<Provider store={store}><MyInfoScreen /></Provider>);

await waitFor(() => {
jest.runAllTimers();
});

const el = screen.queryByTestId("my-info-widget");

//JEST provide us expect 
expect(el).toBeTruthy();
});


it('If TabPanel value is access_request then render UserAccessTabs ', async () => {
getMyInfoMetadata.mockImplementation(() => Promise.resolve({}));

render(<Provider store={store}><MyInfoScreen /></Provider>);

await waitFor(() => {
jest.runAllTimers();
});

// React-testing-library provides firevents with we can mock events like onClick,onChange...etc
fireEvent.click(screen.getByTestId("access_request"));

expect(screen.getByTestId("access-request-panel-title")).toBeTruthy();
});

it('If TabPanel value is my_info then render MyInfo Table', async () => {
getMyInfoMetadata.mockImplementation(() => Promise.resolve({}));

render(<Provider store={store}><MyInfoScreen /></Provider>);

await waitFor(() => {
jest.runAllTimers();
});

fireEvent.click(screen.getByTestId("my_info"));
expect(screen.getByTestId("my-info-table")).toBeTruthy();
});
});

Conclusion

Testing is necessary for a software application’s or product’s effective performance.

Testing improves the sturdiness and error resistance of software. It’s a technique to make that your code is doing what you want it to and that your app is functioning properly for your consumers.

Testing Reactjs apps are no different, and there are numerous libraries available to make the testing experience joyous.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply