How to perform UI Testing of ReactJS Apps?
By The Nerdy Geek, Community Contributor - April 14, 2022
In today’s digital world, life without mobile and web applications cannot be imagined. With the increase in access to the internet and smart devices, consumers seek online intervention to fulfill day-to-day errands. Be it booking a movie ticket online or ordering food, or making bank transactions, everything is digitized. Behind all these seamless and faster user experiences, there are a lot of efficient frameworks; React is one such robust framework.
What is React Library?
React is a JavaScript-based UI development library. Meta (formerly Facebook) and an open-source developer community run it. It is widely used in web development even when React is a library rather than a language. React library was introduced in May 2013 and is now one of the most widely used frontend libraries for web development.
It also offers various extensions for architectural support of the entire application, such as Flux and React Native.
Benefits of using React for developing Web Apps
Some of the core features behind React’s popularity:
- Improved performance: React uses Virtual DOM. It compares the previous states and updates of components and changes only those items in the Real DOM that were changed, instead of updating all of those components again as conventional web applications mostly do. As a result, ReactJS applications are comparatively faster.
- Reusable components: React application is built using Components as the building blocks, with a single app made up of various components. Each of the components has logic and controls, making them individual functioning entities. In React, the components can be reused throughout the application, which in turn dramatically reduces the application’s development time and effort.
- Dedicated tools for easy debugging: React supports a lot of tools that facilitate easier and faster debugging. For example, Meta has released a Chrome extension that can be used to debug React applications.
- Easy creation of dynamic applications: React makes it easier to create dynamic web applications because the load time is significantly low in React due to Virtual DOM as compared to conventional frameworks. Moreover, it also requires less coding and offers more functionality.
- Fast Learning: React is easier and faster to learn, as it mostly combines basic HTML and JavaScript concepts with some beneficial additions.
- Used for creating mobile and web applications: There is a framework called React Native, derived from React itself, that is used for creating beautiful mobile applications. So as a result, React can be used for making both web and mobile applications.
Features of React
React offers some amazing features, making it the most widely adopted library for UI app development, including
- JSX: JSX is a JavaScript syntactic extension. It’s a term used in React to describe how the user interface should seem. You can write HTML structures in the same file as JavaScript code with the help of JSX. The below code shows how JSX is usually implemented in React. It is neither a string nor HTML. Instead, it embeds HTML into JavaScript code.
const name = BrowserStack; const greet = <h1>Hello, {name}</h1>;
- Virtual Document Object Model (DOM): The Virtual DOM is a lightweight version of the Real DOM. Real DOM manipulation is much slower than virtual DOM manipulation. When an object’s state changes, Virtual DOM updates only that component in the real DOM, which is affected rather than all of the components inside that object.
Read More: Getting Started with Selenium and React
UI Testing of a React Web App
UI Testing is essential for creating a great user experience. Let us understand how to perform UI testing of ReactJS Web Apps by testing a ReactJS Web App – The New York Times. To ensure a seamless user experience across different devices and browsers, testing the React Web App across different real device-browser combinations using BrowserStack Live.
Step 1: Enter the New York Times application URL that is under test upon opening BrowserStack Live.
Step 2: Select the Device-Browser Combination for testing the ReactJS Application.
In this scenario, the user is trying to visit the Tech section of the newspaper and preview the list of articles to ensure that the user experience is consistent across different browser-device combinations.
Here are some cross-browser compatibility tests conducted on different browser-device combinations using BrowserStack’s real device cloud:
Windows 11 on Microsoft Edge 99
Google Nexus9 v5.1 on Chrome
Read More: Browser compatibility for ReactJS web apps
Mac Catalina with Firefox
iPad Pro 12.9 2021 v14.6 with Safari
Test Result
As observed, on all of the devices, the ReactJS web app of The New York Times worked consistently with seamless functionality and is providing the same user experience.
UI Testing of React Application Using Jest
After discussing the different aspects of ReactJS, let’s see how we can test ReactJS applications using Jest.
Jest is a JavaScript testing framework that has a great focus on simplicity. It is installed using npm or Yarn. Jest is a kind of test runner that works great for React applications, and also outside of React applications.
Here, using Jest as the test runner, in the below example:
import hello from "./hello.js" describe("my react component", () => { test("is working as expected", () => { expect(hello()).toBe("Hello"); }); });
In the above test:
- it or test: In this, we can pass a function, and the test runner would execute that function as a block of tests.
- describe: This is an optional method and can be used for grouping any number of it or test statements.
- expect: It defines the condition that the test is expecting. This is done by comparing the received parameter to the matcher.
- mount: The method mount renders the full DOM, which includes all the child components of the parent component where the tests are run.
- shallow: It renders only the individual components under test. The method shallow does not render any child components, allowing QAs to test components in isolation.
Read More: Jest Framework Tutorial: How to use it
Creating React UI Test with Jest
In the case of Jest, any files found in any directory with the name __test__ are considered a test. In addition, Jest recognizes any file that has the suffix .spec.js or .test.js. This is done by searching the names of all folders and all files in the entire repository.
Open Application.test.js to write the first test. It checks whether the app component is being rendered correctly and whether the output is specified:
it("ret without crashing", () => { shallow(<App />); }); it("renders Account header", () => { const wrapper = shallow(<App />); const welcome = <h1>Display Active User Account Details</h1>; expect(wrapper.contains(welcome)).toEqual(true); });
In the above case, the first test, uses shallow, to check whether the app component renders correctly without crashing.
The second test checks whether the h1 tag output of “Display Active User Account” is specified in the app component, using toEqual Jest matcher.
Running the Jest React UI Test
You can run the test using the below command
npm run test /* OR */ npm test
After discussing how to run tests using Jest, let’s understand how the React Testing Library works, so as to integrate it seamlessly with Jest and for simulating UI actions.
Read More: How to test React Apps
ReactJS UI Tests using React Testing Library
To build efficient UI tests for ReactJS applications, React Testing Library, a lightweight testing library is meant to test React components. It queries and interacts with DOM nodes to test the React components.
React Testing Library has simple utility methods that simulate an end-user action. Most importantly, it works very well together with Jest, making it an effective integration to test React App components.
Assume a SearchForm React component consisting of input fields and a search button. To test the SearchForm, run the below code snippet written using React Library.
import {render, screen} from '@testing-library/react' describe("SearchForm", () => { test("renders SearchForm", () => { render(<SearchForm/>); expect(screen.getByRole("heading", { name: /location search/i }) ).toBeVisible(); expect(screen.getByRole("textbox", { name: /choose an origin \(optional\)/i }) ).toBeVisible(); expect(screen.getByRole("textbox", { name: /choose a destination/i}) ).toBeVisible(); expect(screen.getByRole("button", { name: /search/i }) ).toBeVisible(); }); });
The above test uses two methods from @testing-library/react:
- Render: It is a utility method of React Testing Library. This method renders a react component into a container and appends it to document.body.
- Screen: is an object exported by React Testing Library and has access to all the query methods that can HTML elements visible in document.body.
Query Methods of React Testing Library
Below are a few helpful query methods of React Testing Library:
- byText: This looks for elements having a particular text content.
- byRole: This will query elements with a certain role that they have been assigned.
- byLabelText: This will try to match a label present in the HTML and return an element that is associated with that label.
- byPlaceholderText: This will look for elements with a placeholder attribute and match the text.
Search variants of React Testing Library
Below are a few helpful search variants of React Testing Library
- getBy: This method either returns an element or an error if an element is not found. Few variations available with getBy are getByText, getByRole, getByLabelText, getByPlaceholderText etc.
- queryBy: This is the same as getBy but it also allows to assert for elements that are not present without getting an error. queryBy have a few variations such as queryByText, queryByRole, queryByLabelText, queryByPlaceholderText etc.
- findBy: This is to assert for any elements that aren’t there yet but will be there eventually. The variants of findBy are findByText, findByRole, findByLabelText, findByPlaceholderText
These were for searching a single element, however, when it comes to multiple elements, we can use getAllBy, queryAllBy, or findAllBy.
Assertive methods of React Testing Library
Usually, all these assertive functions originate from Jest. However, React Testing Library extends this API with its own assertive functions like toBeInTheDocument. All these assertive functions come in an extra package that is already set up for you when using create-react-app.
Some of the handy assertive methods are:
- toBeInvalid
- toBeRequired
- toBeValid
- toBeVisible
- toContainElement
- toContainHTML
- toBeDisabled
- toBeEnabled
- toBeEmpty
- toBeEmptyDOMElement
- toBeInTheDocument
No matter which framework you choose for testing your application, it is important to perform tests on real devices and browsers over emulators and simulators for accurate results. Using BrowserStack Real Device Cloud, you can access 3000+ browser-device combinations offering a wide coverage, allowing you to test end to end under real user conditions.