Turn your manual testers into automation experts Request a DemoStart testRigor Free

React Testing

React Testing

ReactJS, or React, is an open-source JavaScript library used for building interactive user interfaces and web applications. React is a frontend library that gradually became the most popular web framework. As of 2022, React is the second most used web framework after NodeJS. React was created by Jordan Walke, a Software Engineer at Facebook. His early prototype was called “FaxJS.” In 2017, Facebook introduced React Fiber, a new rendering algorithm that replaced the old rendering algorithm – stack, thus eliminating the slow process of rendering complex animations. React is maintained by Meta (formerly Facebook). The latest version, 18.2.0, was released in 2022. React mainly focuses on the View layer of the application’s MVC (Model-View-Controller) pattern.

Testing in React can be classified into three levels:
  • Unit Testing
  • Integration Testing
  • End-to-End Testing

Let’s dive deep into each of them.

Unit Testing

As the name implies, unit testing is simply testing each unit logically isolated in an application. A unit can be a function, class, or component. Unit testing is performed to capture bugs earlier during the development cycle. There are two approaches to performing unit testing:
  • Snapshot Testing
  • DOM Testing

The tool we can use for both methods is called Jest. Support of other libraries like Enzyme or React-testing-library is required for DOM testing. We will cover this further down the line. Now let’s look into Snapshot testing.

Snapshot Testing

When we perform snapshot testing, the test case using the test renderer generates a quick serializable value for the React tree. Then the generated tree is compared with the reference stored for that particular test case. If the comparison matches, the test case passes; else, it’s a failure. Usually, the failure happens in case of an unexpected change or if any new functionality was added. We can perform this using Jest.

Jest

Jest is the most popular unit testing framework used across all JavaScript codebases. Using Jest, we can access the DOM via Jsdom. Jest provides a great iteration speed. Consider a sample test script for the Link component.

import renderer from 'react-test-renderer';
import Link from '../Link';

it('renders correctly', () => {
  const tree = renderer
    .create(<Link page="http://www.facebook.com">Facebook</Link>)
    .toJSON();
  
  expect(tree).toMatchSnapshot();
});
While executing this first time, Jest creates a snapshot as below:
exports[`renders correctly 1`] = `<a
  className="normal"
  href="http://www.facebook.com"
  onMouseEnter={[Function]}
  onMouseLeave={[Function]}>Facebook</a>`;

This snapshot will be committed along with the unit test code base and code-reviewed. This snapshot will be taken as a reference for future executions. So the test case fails when there is an unexpected change in the code snippet. Consider if a new functionality has been added, so we need to update the snapshot; that can be done by executing the command – jest --update snapshot. This will regenerate a new snapshot.

DOM / Functional Testing

Snapshot testing captures the whole rendering and compares it with test iterations. In DOM testing, we test the functionality by adding assertions. To achieve that, we need to use other libraries such as Enzyme or React Testing Library.

Enzyme

The Enzyme is an open-source JavaScript library used for react apps. The Enzyme helps to manipulate, simulate, or add assertions to the script to validate the output. Using Enzyme, we can find elements and interact with them.

Jest can be used with any Javascript app, but Enzyme works only with React. Jest can be used without Enzyme, although Enzyme requires a test runner.

Below is a sample script:
import Enzyme, {shallow} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import CheckboxWithLabel from '../CheckboxWithLabel';

Enzyme.configure({adapter: new Adapter()});

it('CheckboxWithLabel changes the text after click', () => {

  // Render a checkbox with label in the document
  const checkbox = shallow(<CheckboxWithLabel labelOn="On" labelOff="Off" />);

  expect(checkbox.text()).toBe('Off');
  
  checkbox.find('input').simulate('change');
  
  expect(checkbox.text()).toBe('On');
});

DOM is more effective when compared to Snapshot testing because it covers more scenarios. Snapshot testing can be considered smoke scenarios for unit testing.

Integration Testing

In integration testing, we check how components work when they are integrated. When we perform unit testing, we mock responses from other components. But when performing integration, mocking is not required. Integration testing for React apps is done by manipulating the component state or DOM in react lifecycle methods.

For executing integration testing, we can use the following tools:
  • Enzyme
  • React Testing Library

Since we have already gone through Enzyme, let’s get into more details about react-testing-library.

React Testing Library

RTL is built on top of DOM testing libraries by adding APIS for working with React components. RTL provides an API that returns HTML elements and also has a querying function that queries by text content or HTML data attributes. Even if we use RTL, we need a runner library like Jest or others.

Let’s look at a sample RTL test case:
import React from "react";
import { render, screen } from "@testing-library/react";
import user from "@testing-library/user-event";
import { fetchPost as mockFetchPost } from "../api";
import App from "../app";
  
jest.mock("../api");
  
test("Can search for a post using its ID", async () => {
  const mockPost = {
    id: "1",
    title: "Post Title",
    body: "Post Body",
  };
  mockFetchPost.mockResolvedValueOnce(mockPost);
  render();
  
  expect(screen.getByText(/submit/i)).toBeDisabled();
  expect(screen.getByText(/welcome/i)).toBeInTheDocument();
  expect(screen.getByText(/search.*post.*id/i)).toBeInTheDocument();
  
  user.type(screen.getByLabelText(/post id/i), mockPost.id);
  const submitButton = screen.getByText(/submit/i);
  expect(submitButton).toBeEnabled();
  user.click(submitButton);
  
  user.click(screen.getByText(/back.*home/i));
  await screen.findByText(/welcome/i);
});

End-To-End Testing

In E2E testing, user workflows are considered critical to the business. So testing team executes these scenarios in real browsers. Using manual testing, we can achieve this, but it’s a process that takes time and can only be completed in a limited time frame; also, it’s more error-prone. Automation is the other way, and for that, we have many options available in the market. This is where new tools are coming up in the market every day. From the whole list, we have short-listed a few automation tools; let’s look into each one of them:
  • Cypress
  • Playwright
  • Selenium
  • testRigor

Cypress

Cypress is an open-source automation tool in JavaScript. Cypress provides a faster execution time with an easy setup option. Automation scripts are written in JavaScript and use Behavior Driven Development patterns. Scripts are written in the Mocha framework and use Chai as an assertions library. You can only use JavaScript or TypeScript to create tests in Cypress.

See a sample Cypress script below:
describe('login and logout', () => {
    it('login', () => {
      cy.visit('/');
      cy.getByTestId('username').type('user123');
      cy.getByTestId('password').type('pass123');
      cy.getByTestId('submit').click();
    });
    it('logout', () => {
      cy.getByTestId('home')
        .should('exist').then(function (home) {
          home.find('[data-cy=logout]').click();
        });
      cy.url().should('include', '/login');
    });
  });

Playwright

Playwright helps to execute E2E tests on browsers like Chrome, Edge, Firefox, Opera, and Safari. It’s a platform-independent tool that can work with most operating systems. Playwright has useful features like auto-wait, parallel executions, and trace viewer.

Let’s look at a sample Playwright script:
const { test, expect } = require("@playwright/test");
const { default: Input } = require("../src/components/Input");
  
test("homepage has E2E Testing with Playwright", async ({ page }) => {
  await page.goto("http://localhost:3000/");
  await page.screenshot({ path: "screenshot/homepage.png" });
  await expect(page).toHaveTitle(/React App/);
  const getStarted = page.locator("text=Get Started");
  await expect(getStarted).toHaveAttribute("href", "http://localhost:3000");
  await getStarted.click();
  const inputField = await page.locator("id=nameInput");
  await inputField.fill("codedamn");
  await expect(inputField).toHaveValue("codedamn");
  await page.screenshot({ path: "screenshot/inputField.png" });
});

Playwright is based on BDD and supports the Mocha and Jasmine frameworks. We can also perform basic API operations with this tool as well. If there is a request with redirecting URLs, Playwright won’t be able to execute that.

Selenium

Selenium used to be one of the industry’s favorite tools until a few years back. We don’t have to go much into Selenium, as everyone knows about this legacy tool. Many pieces of information and tutorials are available online about it. But its vast, complex structure and subpar test running speed and stability made the companies move out, looking for some lightweight tools.

testRigor

Most of the tools we discussed here for E2E automation require programming knowledge. When it comes to testRigor, the key differentiators from any other solution on the market are no-code, speed and ease of test creation, and virtually obliterated test maintenance.

Let’s review a sample testRigor test:
click "Sign in"
enter "jacob" into "Username"
enter "jacobs-secure-password" into "Password"
click "Verify me"
check that sms to "+12345678902" is delivered and matches regex "Code\:\d\d\d\d" and save it as "sms"
extract value by regex "(?<=Code\:)[0-9]{4}" from "sms" and save it as "confirmationCode"
enter saved value "confirmationCode" into "code"
click "Continue to Login"
check that page contains text "Welcome, Jacob!"

You may need clarification about whether the above is a manual test case or an automation script. Since testRigor is independent of the programming language, all scripts are written in plain English (unless using Regex or building API testing). The most significant benefits here are the absence of implementation details and allowing anyone on the team to build automated tests and increase test coverage.

A few advantages of using testRigor are:
  • You don’t need to use any element locators in testRigor. So while selecting an element based on how an actual user would describe it, testRigor’s integrated AI captures multiple locators for that element. The test will still pass even if one of the locators changes – which is exactly what we want for an end-to-end test from a customer’s perspective.
  • testRigor is a cloud-hosted tool, so there is no need to put effort into setting up the tool and infrastructure. Once logged into the account, users can start creating scripts immediately.
  • testRigor supports cross-browser testing, API automation, desktop, mobile, visual, load testing, etc. It aims to be the only tool for functional end-to-end testing you will ever need. You can read more about key features of testRigor here.

Time and effort are significant factors affecting the company’s profit. Using any tool that requires time and effort to set up and debug may be reconsidered as the market shift is currently more towards a “first to market” strategy.

Join the next wave of functional testing now.
A testRigor specialist will walk you through our platform with a custom demo.