React unit testing

Learn via video courses
Topics Covered

Overview

React Unit testing is a testing method that tests a single software unit in isolation. Unit testing a React app means testing a single React component.

"React Unit testing is a great discipline that can reduce bug density by 40% to 80%." - Eric Elliotte

React Unit testing helps you test the individual functionality of your React components. In addition, each error in your code can be self-identifying from the start, saving you time in fixing it at a later stage.

React Unit tests greatly improve the quality of your code. This helps developers identify the smallest possible bugs in a unit before moving on to integration testing.

Distinction Between Unit Testing, Integration Testing and End-to-End Testing

Unit Test: Unit test is the simplest test to write because you can expect a certain result for your input. No dependencies or complex interactions.

Integration Test: Integration testing verifies that the individual modules or services that make up your application work together well. The purpose of this level of testing is to find bugs in the interactions of these software modules when they are integrated.

End-To-End: End-to-end testing simulates a specific user interaction flow with your app. For example, click or type text.

Different types of testing

Unit Test

Unit tests are your first line of defence against bugs. These tests are meant to run locally and check the most basic logic pieces in your code.

Unit tests are meant to test every function/potential logic path, whether it's a function, class, or something else. In fact, writing unit tests for every possible code flow is called 100% code coverage. Realistically, good code coverage looks closer to 80%. The higher the coverage, the more reliable your code will be when unit test pass.

You can use Unit tests everytimes. Whether you're writing code for a school or deploying code to billions of users, unit testing is an easy way to find bugs quickly.

Integration Test

Integration tests ensure that various blocks of code interact successfully in your on-premises environment. A chunk of code can come in many forms, but integration testing typically involves validating the interaction of services and APIs. Integration tests are generally local, so you may need to simulate different services.

An effective and scalable codebase is usually made up of many small pieces of code that work well together, but how do you know if they work well together? Integration tests glue the services together. API calls or database queries. This is useful when your code base grows and contains more complex interactions.

Integration tests are not as ubiquitous as unit test, but there are many reasons to use them:

  • To test your app's database interaction, or the interaction between your app's frontend/backend
  • Implement a contract test to validate that the API is defined as expected

End-To-End Test

End-to-end testing (E2E testing) is a method of validating the behavior of deployed code from the user's perspective. Since we automate the user simulation interacting with the system as a black box, all that matters is whether the user's actions correspond to the correct output in a timely manner. These tests are typically run in a development or staging environment to match as closely as possible user interaction in production.

E2E testing is like practice exams and is the closest thing to real business. Validating that your code works in near-real-world conditions increases your confidence that your code will work in the real world.

E2E testing is complex and difficult to implement. These are most common in production code, so if manual testing is more efficient, it might save you time on pet projects or schoolwork. In summary, he should use E2E testing when:

  • You are not the only user.
  • Have sufficient infrastructure for staging or development environment

Purpose of Unit Test

Test is a great area where defect density can be reduced by 80%. It also has other important benefits such as:

  • Improves code architecture and maintainability.
  • Here's some quick feedback to test if your changes worked.
  • Provides better security when adding new features or refactoring existing features.

React Unit tests are our best friends. Make changes and refactor with confidence without worrying if your application still works. Plus, it avoids errors and hours of debugging to ensure your code works properly.

for example, I have a link component that internally redirects to a SPA via a prop and I added a new prop called href that redirects to an external link such as youtube.

How can I make the to behavior work fine and not break the existing flow? Test by going screen by screen? Ask other devs checking the screen? No, write a unit test to make sure you're inside each time you click on a link that supports navigation, write another test for the href behavior.

Prerequisties for React Unit Testing

To run React unit tests, we use two very popular libraries: Jest and Enzyme. Jest is a library created by Facebook that has become very popular in recent years(other libraries such as Mocha and Chai can be used). Jest will help you make all the assertions and Enzyme will help you render your React components in test mode. we'll see both in action in the next section.

Introduction to Unit Testing in React

React Unit testing is a technique you can use to test a unit (the smallest piece of code that can be logically isolated within an application). functions, class methods, subroutines, etc. In our case, we mostly test functions and React components.

React Unit testing is a level of software testing where individual units/components of software are tested. In the React world, this means testing a single React component or pure functionality.

Unit Testing in React with Jest and Enzyme Frameworks

Jest

Jest is a JavaScript testing framework that allows developers to run tests using JavaScript and TypeScript code, and integrates easily with React JS. Jest is a JavaScript/TypeScript framework for testing that runs tests, checks coverage, allows mocking, and more. Jest is a great JavaScript testing framework designed to ensure the correctness of any JavaScript code base. It allows you to create tests using an accessible, familiar, and feature-rich API and get results quickly.

Note: You need to install Jest before writing test cases. Running the create-react-app command will automatically install Jest into your react application.

Create a New React App

Let's create it with the following command:

If you open the package.json file, you'll see that Jest and React Testing libraries are supported by default when creating a React project using create-react-app. This means you don't have to manually install it.

Create a Component

Counter.js:

It's important to note here the data-testid attribute used to select these items in the test file.

Write a Unit Test For the React Component

  • Tests are usually written in test blocks.
  • Inside the test block, render the component you want to test first.
  • Select the element you want to manipulate.
  • Manipulate these elements.
  • Verify that the results are as expected.

Explanation :

  1. Test blocks can be written with test() or it(). The two methods each take two parameters:
    • The first parameter names the test. Example: Increment a counter.
    • The second parameter is a callback function that describes the actual test.
  2. Use the React test library's render() method in the above test to render the Counter component in the virtual DOM.
  3. The screen property of the React testing library helps you select the items you want to test based on the previously provided test ID.
  4. To interact with buttons, use the fireEvent property of the React testing library in your tests.

And finally, it asserts that the counter element contains the value '1'.

Run the test case using the following command:

Output

Jest

Enzyme

Enzyme is a library used for testing React applications. Designed for testing components, you can write assertions that simulate actions to check if your UI is functioning properly.

Enzyme is a JavaScript testing utility for React that makes it easy to assert, manipulate, and iterate your components. Created by Airbnb and later transferred to an independent organization. Developed around December 2015. It provides easy methods for finding elements, rendering components, and interacting with elements.

Enzyme Installation

To start using Enzyme, install it via npm using the following command.

Writing the First Test Case

Follow the steps below to create a test case in your React application.

Render a simple button called Click Me with the following code.

App.js:

App.test.tsx:

Explanation : We kept the app component's flat renderer in a wrapper variable. You can connect the button tag with the length and text of the button. And you have to check that the passed text matches the toEqual matching function.

Run the test case using the following command:

The test results will be displayed below.

Enzyme

Test with User Interaction

Let's create a new test case that simulates a button component click and checks the dependent actions.

App.js:

App.test.tsx:

Now run the Command:

Output

test-with-user-interaction

Test Case For State Variable

Let's create a new test case that uses the state variable to check the disabled/enabled status of the button

App.js:

App.test.tsx:

Explanation : Firts of all we have to import shallow from enzyme and import Adapter from enzyme-adapter.

Then we have tests above and we use the describe layer to get the component under test. You can proceed by providing props and values that you expect the test to pass.

The first test verifies that the props we passed to the shallow component match the mock props we created above.

The second test passes user properties to the shallow app component. Then check to see if you can find a element that corresponds to what you have in your app component. Then run the test and you will see that the tests run successfully.

Test with Router

If you have a router in your React app then, how you will test it?

Explanation :

In the above code, we saw how to use state variables and input field pass-by-value events to handle the router.

Conclusion

  • React Unit tests are the easiest way to improve the quality of your React applications as they help you find bugs and bugs in your code.
  • You have learned some Jest testing techniques using the enzyme testing library.
  • In any project, it's important to write the simplest type of tests, React unit tests, to increase confidence in the correctness of the code you write.
  • So React unit testing turned out to be a must for developers. Seems like extra work, but testing becomes a must when it comes to performance improvements and a great user experience with less bugs.
  • You learned how to run React unit tests using the Jest and Enzyme frameworks. Incorporating this into your toolkit can also help ensure your app's stability and improve code quality.
  • The debugging process is greatly simplified by React unit tests.