React Testing Tutorial: A Guide To Testing React Apps
Posted On: March 17, 2022
22 Min Read
Although testing React applications is not as straightforward as other libraries or frameworks, it’s possible. In this article on React Testing, we’ll explore some methods of testing React components by first looking at a basic test, and then we’ll dive into some more advanced testing principles and best practices.
Let’s get started!
TABLE OF CONTENTS
An Introduction to React
The React library can be utilized as a base for creating Single page applications and mobile apps. The React library was originally released under Apache License 2.0 in May 2013, but later the licensing type got changed a few times due to several reasons. As of today, when this article is being published, the React library is offered under the MIT License. Irrespective of the above change in License type, the adoption of React library from the day of its release until now is humongous. Here is the GitHub Repo for the React library.
As per the recent survey, at least 10+ Million websites are using React for front-end application development. Another survey conducted by Statista reveals that React has surpassed JQuery with a total usage stat of 40.14% to become the most widely used web framework among developers across the entire globe. This online survey by Statista was carried out worldwide during the middle of 2021 for a period of 30 days, and the results were published by Aug 2021. The total number of respondents to this survey was 67,593.
Here are some of the popular web applications built using React:
- Whatsapp(Web version)
As I have mentioned before, the React library can be utilized as a base for creating mobile apps, here are some of the popular mobile apps built using React Native (uses React library):
Use JSX to build UI components like Babushka dolls
Most of us would have come across Babushka dolls/Stacking dolls during some part of our life. It represents how multiple generations are carried over by a mother. It is a set of dolls that represent a mother carrying a child within her, and the child in the future carries/gives birth to another child leading to a chain of heredity of a family.
In the ReactJS application, similar to how Babushka dolls are made of multiple wooden pieces/blocks, React library encourages the developers to build user interfaces of web applications based on components.
Be it a web application or mobile app, instead of creating the UI elements as one monolithic segment, React encourages the developers to design the UI elements into smaller components. In the programming world, it is always recommended to design/develop things in a modular way for better extensibility, flexibility, and easy maintenance. The same widely accepted principle is propagated by the React library as well.
Moreover, the APIs of React’s core library make developers’ work easy for developers to achieve that goal. The components created can either be used individually or can be combined to make a single large page in the application. Hence this component-based approach of React is compared with Babushka dolls.
Here is a sample code snippet of JSX in React:
<!-- This div element will hold the component defined using the JSX -->
<h1>Hello, I am a sample JSX code snippet</h1>,
Now that we have seen an overview of React and how the React UI components are built using JSX, let’s dive into the main subject of this article on React Application testing.
Also read – Design Patterns For Micro Service Architecture
What is the need for React testing?
Why do we need to test a React application? Here are the top three reasons:
- First and foremost, everyone needs working software. In today’s distributed processing-based application world, it is not wise to assume that every piece of the software stack will work 24*7 in a reliable manner. When we introduce a change or update an existing piece of code, things might or will break, and it is wise to expect the worst. However, as a software development team, we can be prepared and play our role to minimize how our application can fail by carrying out tests based on our assumptions.
- Secondly, the process of TDD (Test Driven Development) tends to help the developers to write efficient code. If not before, at least we must have the test cases developed to cover the failures. Having some test codes is always better than having no test-related code in the application.
- Last but not least, introducing testing into your application development lifecycle means the organization can release the latest feature into their apps more frequently and confidently. Furthermore, by means of Continuous Integration (CI) or Continuous Deployment (CD) tools, one can ensure testing is carried out as part of the application deployment process. The high-level idea is that if the tests get passed, the latest version of the application gets deployed to whatever instances run the application.
Also read – 31 of The Top CI/CD Tools Available Today
What to test in the case of a React application?
The React application that you are dealing with might be simple or quite sophisticated at times. In any case, it is always good to have priorities identified before carrying out React testing. Unfortunately, there is no Rule of thumb for determining which aspect of your React application needs to be prioritized. However, the following are some good items to start with:
- Identify the features which add more business value to your application and carry out testing. For example, in the case of the Netflix application, searching for a movie and playing the video is an important feature. So, consider that area as a prioritized feature to test.
- Execute border case/edge case scenarios in those high valued features.
- Identify the most used React components in your application and test those.
- If your application serves a large user base, such as Netflix or Amazon, ensure to test the application for stress and performance load.
- Include the testing scope for basic React component testing, which includes:
- User interactions with the components, such as OnClick or OnSubmit events
- Conditional renderings such as impact due to State changes or Prop changes
- React hooks (if hooks are defined in your React apps)
What are the libraries/tools required to perform React testing?
Testing a web application/mobile app requires other software and tools. However, there is no need for us to invent/develop these testing libraries/tools now. The developers of the open-source community have already contributed an incredible amount of effort to build a large number of libraries and efficient tools for this purpose. Here are a few of such libraries and tools to aid in React testing:
A Test Runner is software that aids in running the tests of the React application either by an individual selection of React script files by choice or in groups or as a whole test suite. Once the test run is completed, it also reports back the success or failure information in a human-readable manner.
The React team recommends using the Jest library for this purpose. It provides the ability to access the DOM elements of your web application through jsdom, which is close enough to mimic the behavior of browsers in several cases. One could also use Mocha and Jasmine for React testing. However, Jest is the widely used test runner by the React community.
While developing tests for your React application, you might want to focus only on components of interest instead of including other variable factors that could deviate from your unit test goals. This is where a mocking library comes in handy to unit test your React components.
Testing this way aids to have a focus built on the component under test and promote modularity. Again, in this case, Jest comes with out-of-the-box support for creating test doubles, but other libraries support such mocking features, example: Sinon (http://sinonjs.org/)
Often it is required to test the outcome of conducted tests, such as does length equal breadth for a square? This is where the assertion library’s role comes into play. Once we start getting involved in making assertions, sooner we will get into the need for sophisticated “Assertion Matchers” and in a React ecosystem, Jest comes with built-in assertion methods to make the React testing code developers’ job easy with Jest assertions.
Libraries aligned to the framework
To make testing of React components easier, the open-source community has developed some good libraries such as React Testing Library and Enzyme. Both these libraries offer a set of helper methods that can be utilized to test React components without depending on how these components are implemented. The React team’s recommendation is to use the React testing library for React testing.
While we are at this juncture, I would like to highlight a key difference between the Enzyme and React testing library. Enzyme library allows one to carry out either a shallow component testing (a way to test a component without considering its children/dependent components) or complete component testing (a way to test component including its children/dependent components), whereas React testing library does not support a direct way to shallow test the React components. However, the developers could use Jest for faking the dependent or child components and could indirectly achieve the shallow component testing in React.
Running the application in a browser and carrying out the testing matters a lot in the case of a web application. Performing browser testing is a march towards the goals of end-to-end testing of any web application, and it helps to identify/prevent regression in the workflows.
End-to-End Test frameworks
Frameworks like Selenium, Cypress, and Puppeteer provide an easy, fast, and efficient way to test any application that runs on browsers. These frameworks also allow one to
- Set up tests,
- Write tests,
- Navigate across different routes defined in the application to carry out tests on different user interfaces
- Monitor the tests as it gets executed, and while you are making changes to the web application,
- Built-in tools to promote debugging of test runs as an easier task, and
- Records test results for post-mortem analysis.
Also read – Selenium vs Cypress – Which Is Better
How to test React applications?
As far as testing goes, React has a few different types of tests you can write: unit tests, integration tests, and end-to-end (E2E) tests. Unit tests are the fastest type of tests because they only test a single unit of code in isolation. Integration and E2E tests are slower because they require the whole app to be running in a browser or simulated environment. The higher up the test pyramid you go, the more brittle your test suite becomes.
In this section of the React testing tutorial, we will discuss how to carry out:
- Unit tests
- Snapshot tests
- Integration tests
- End-to-end tests
Also read – Perform ReactJS Visual Testing On Cloud
How to carry out Unit tests?
To give an example: let’s say, we have a functional module in our React application to generate UUID for some processing needs of the application, we can have a Unit test developed to test that particular function returns an expected value type, format, and in an expected length. This is just an example of carrying out unit testing on a non-UI element/component.
Similarly, we might need to develop a unit test for testing a UI component in our React application, such as a unit test for testing a commonly used button component across several screens. For example, let’s say we have a Delete button in red color (to provide a distinct visual cue to the users), and we would need to test if this particular React component’s property is always in Red irrespective of how many changes are going to occur in our React application in future.
As per the recommendation, unit tests should be larger in number and should cover at least 70% of your application logic. Once the unit tests are developed, and if you have a complex application that resulted in several test cases to execute, there might be a few of the following challenges you would like to overcome:
- How to minimize the time taken by the test runs?
- How to test the application in a different environment to test the React application’s behavior in each of those environments?
To address these questions, what we need is a possibility of performing parallel testing within an environment triggering the same tests in multiple instances based on different environment setups to ensure coverage in terms of environment variation requirements.
With cloud testing tools like LambdaTest, you can integrate your framework and language of choice with the Selenium test suite and have a ready-made solution not only for the above scenarios but many more. For example, you can see in the following screenshot: you are given plenty of frameworks and languages to choose from for carrying out your tests. Jest is one among them.
Once you have selected Jest, you will be taken to another screen with detailed instructions on how to carry out the test setup, code samples, and test execution in the LambdaTest platform.
You can sign up on LambdaTest for free and go for a ride to explore how you can automate things with the LambdaTest platform.
How to carry out Snapshot tests?
It is very useful to plan and conduct Snapshot tests in the case of web applications. It serves as a useful technique to ensure the User interface of your React application does not change unexpectedly.
In the case of React testing, snapshot testing in general deals with taking a snapshot of how a React component renders, then compares it against the reference/base snapshot file created for the purpose of verification. If the compared snapshots fail to match, then the test will fail, else it would pass.
In case, if you are expecting a change in the React component, due to the new feature you are working on, then by process, you must generate the latest snapshot of that particular React component or UI and update the latest snapshot in the test reference folder. By doing so, your snapshot test of that component/UI would get passed.
Here are some of the approaches that you could follow through to achieve your Snapshot testing goals:
- Non-browser approach
- Rendering and browser-based approach
As part of this approach, you can make use of the react-test-renderer library along with Jest to easily create a serializable value of the React DOM tree (without rendering the actual graphical user interface) corresponding to the React application under test. In this approach, the snapshot is treated as a rendered JSON output and compared for match/mismatch against the pre-defined JSON output.
Jest Framework lets you assert a snapshot of a UI element/react component with readily available methods such as toMatchSnapshot/toMatchInlineSnapshot.
Once you have developed your test suite for snapshot testing, you can execute the tests using npm or yarn commands in your local machine or test environment. Or, if you are dealing with a large number of test cases and are in need to run the tests in parallel using multiple instances to shorten the time duration, you could use the LambdaTest Cloud Selenium Grid. With LambdaTest cross browser testing platform, you could improve your team’s productivity and efficiency by launching your tests on 3000+ Desktop and Mobile browsers.
Rendering and browser-based approach
As part of this Snapshot testing approach, the snapshot is treated as an image snapshot taken based on the actual rendering of the UI component in our React application. This is then compared against the base/reference snapshot image and tested for a success/failure case.
Manually executing a Snapshot test on browsers and verifying the results for hundreds of UI components in your web application would be tiresome work and not a path you should choose to travel on. You would need a platform that could help you to automate such testing and give you the finalized result outcome with minimal involvement and time being spent.
With LambdaTest’s Automated Screenshot testing capability, just by a single click, the testers will be able to spot unexpected changes (if they are introduced) in your React application. Whatever the UI changes are related to, be it Icon Size, Color used in the background, UI Layout, Font size or style, the position of the UI element, etc., can be easily identified.
With this Screenshot Testing Tutorial, you will learn how to perform Automated Screenshot Testing on the LambdaTest platform.
How to carry out Integration tests?
The main aim of carrying out integration testing in React applications is to ensure that two or more modules can work well together.
For instance, your React application might deal with Database server interaction on initiating certain events from React application’s UI, and hence to cover that interaction from a testing perspective, you must develop an integration test to verify that your server and database are communicating and exchanging information as expected.
Also, the integration tests shall deal with testing the React application through its user interface in a browser. These tests may simulate user click events, form submit events, user input, and other normal user interactions that initiate various business operations in the React application.
It is because of this complexity involved in the Integration tests, as it deals with more than one unit/module to be tested, developing integration tests take more time. Therefore, it is ok if the number of integration tests is less in number than that of Unit tests.
You can use the React Testing Library along with Jest or you could use Enzyme GitHub Repo for developing your integration tests.
How to carry out End-to-End tests?
End-to-End Tests must imitate the end-user interaction with the React application, and it involves testing the entire system. This is where evidently all the dependencies and complexities of the React application come into play.
As a matter of fact, UI tests are more expensive and difficult to create and maintain the wide variety of environment requirements (think about the various hardware and software versions that need to be involved). Thus, it is ok to have comparatively a less number of End-to-End tests than that of unit tests focusing only on the critical application path. However, keep in mind that you cannot ignore it completely though.
There are multiple approaches to handle end-to-end React application testing:
- In-house manual end-to-end testing approach
- In-house automated end-to-end testing approach
- Using a platform to perform manual end-to-end testing
- Using a platform to perform automated end-to-end testing
In-house manual testing approach
An organization can set up the required environment for testers with required hardware machines, operating systems, and browsers to carry out manual end-to-end tests. Once the environment is ready, the testers can individually open the browsers and access the React application to test the UI screens one by one.
This approach involves a considerable amount of time, effort, and cost from the Organization and its resources.
In-house automated testing approach
Again, in this case, the Organization must set up the required environment for testers with required hardware machines, operating systems, and browsers to carry out manual end-to-end tests. Considering that the testing team has developed automation scripts by Integrating Jest scripts with any framework such as Selenium WebDriver or Cypress, once the environment is ready, they can initiate the end-to-end tests.
This approach involves a considerable amount of time, effort, and cost with respect to the environment setup that deals with multiple machines, operating systems, and browsers.
Using a platform to perform manual end-to-end testing
We have to test our React application in the maximum possible environment flavors (be it Windows, Mac Operating system or let it be Chrome browser or Firefox, etc.), to assure our application would work just fine irrespective of the environment used by the end-user for accessing the React application.
Since the count of machines, operating systems, browsers, and various versions of each of the software involved in the environment setup are enormous in numbers, we could use LambdaTest’s cloud platform to have the required infra setup in no time and execute our test cases.
LambdaTest’s Real Time Browser testing is an excellent feature to carry out manual live testing of your web pages. Just enroll for an account in LambdaTest (if you have not done so already) and try the features available on their platform.
Given below is the screenshot taken from LambdaTest’s Real time – Browser testing interface.
With this Real-Time Testing Tutorial, you will learn how to perform Real-Time Testing on both desktop & mobile browsers on the LambdaTest platform.
Using a platform to perform automated end-to-end testing
Let’s assume that we have developed automation end-to-end test scripts for our React application by Integrating Jest scripts with any framework such as Selenium WebDriver or Cypress. We could use LambdaTest’s Selenium Automation Grid for carrying out Selenium automation testing automation tests on a highly available, secure, and scalable infrastructure based on Selenium.
You can run your custom-made Jest test scripts over an online browser farm of 3000+ browsers, and operating systems. You can get more information on how to test your React application based on Jest with Selenium on LambdaTest.
In this article on how to test react applications, we talked about how to go about React application testing. We began by introducing the React library, followed by an explanation of how Babushka dolls are related to React components for better understanding.
Next, we focused on What is the need for React testing and what to test in a React application. We also listed the tools and libraries used in React application testing.
We then moved on to the topics dealing with Unit testing, Snapshot testing, Integration testing, and End-to-End testing of React applications. We have also seen the latest trend in carrying out the React application or any web application testing using the LambdaTest platform in a smarter and easier way. Learn to implement react testing with this react end to end testing guide.
Frequently Asked Questions (FAQs)
How is testing done for React?
The Testing Pyramid is a framework that can assist both developers and quality assurance professionals to create high-quality software. It shortens developers’ time to determine whether a change they made breaks the code. It can also aid in the development of a more dependable test suite.
Where can I test React code?
Testing can be a challenge, and finding the right tool that fits your workflow can be even more of a challenge. When it comes to testing React applications, there are a few testing options available, of which the most common ones known are Enzyme and React Testing Library (RTL).
Is React testing library Jest?
React Testing Library, in contrast to Jest, is a state-of-the-art React testing library. It’s the best way to write tests for your components.
Got Questions? Drop them on LambdaTest Community. Visit now