Javatpoint Logo
Javatpoint Logo

Unit Testing in React

Unit testing is a method of testing that tests the individual software unit in theprocess of isolation. Check the output of a function for any given input.

It means verifying that the component renders for any specific accessory to react components.

In other words, to writing a unit tests is also alike writing code that verifies the code works as expected.

What is the Distinction between Unit Testing, Integration Testing, and End-to-end Testing?

A unit test tests the smallest code unit, which is possible, and any dependencies the component may have.

Integration tests test the work of multiple components that work together. The tests give the best understanding of user experiences with the application.

The downside of testing is that finding the component that caused the test to break is more complicated. While we failed in unit tests that indicate a problem in a particular component, a broken integration test can be caused by many components, and it's not an explicit component that caused it.

End-to-end testing is called user interface testing, which takes integration testing by testing the entire system from the user's point of view.

The tests cannot know the system, and it focuses on the system from the point ofview of users.

The tests click by the application and verify the user interface matches the expected results, and it is the result of manual and automation testing.

The straightforward thing is to look at the pyramid oftests to explain the tests which will work together:

Unit Testing in React

Unit test is the base of the pyramidbecause it is supposed to lay the foundation of tests. Itis easier to write and is the best written for writing code and fixingbugs.

What is the purpose of unit tests?

There are many reasons why unit tests will be helpful. Some of them are below:

  • It exercises your code
  • It prevents the regressions
  • Faster feedback in the development

These are valid points, but the main advantages of writing unit tests are to improving the coding style.

Writing the tests during or before implementing the feature gives us a better idea of the requirements. Write the code that is loosely coupled and easier to test. It was with refactoring a code snippet to make it easier to test in the first place.

For example, we extract the functions into the separate file to make the code easier to test. After that, the result is less coupled.

The primary intent of unit tests:

It has prevented us from sending bugs to production on a few occasions.

Unit tests help us with all points. They form the foundation of any solid test suite for a good reason.

When should you write a unit test?

There are so many opinions about when to write the unit tests. We can write by Test-Driven Development (TDD) which tells us to write test cases before writing the code, and prefer to write the unit tests when the code has been written.

The most significant advantage of unit testing is when you write tests during the actual deployment, that doesn't mean we have to follow the advice.

It is the best idea to write test cases in the following situations:

  • During or before the implementation of new functionality
  • Before and during refactoring
  • Before correcting a mistake

What tools do we need to get started with unit testing in React?

So now we know that unit tests are, used to start writing the first test. Let's see at the tools that will use to write automated tests.

To start writing unit tests in React, you only need the below two types of tools.

  • Test runner
  • Testing utilities

Choosing a test runner for React

What is a test runner?

The test runner is a program that runs the tests (in the case of unit testing) and allows us to recognize when the tests pass or fail.

  • It is an essential tool to remove friction by automating the execution of unit tests. It allows doing the unit tests as apart of CI pipeline (continuous integration).
  • It removed friction which will lead the developers to run tests more easily.

Testing a component involving state

Note that there are two sets of testing where we can testour class component.

  • Behavioral. We can simulate a click on the button and see the button's text has changed. We are seeing the behavior of user and testing the expected change.
  • Component-based. It tests the toggle method of the component and looks if it does then what we expect it to do. Itis helpful when the toggle function is more complicated, and wants to test different scenarios of unit testing.

The combination of two gives us higher confidence.

Prerequisites for React unit testing

We use two viral libraries named Jest and Enzyme to do the unit testing. Jest is a very popular librarywhich is written by Facebook and itbecamepopular in the sometimes (You could use other libraries such as mocha or chai in place of Jest).

Jest helps us do all the assertions, and Enzyme helps usrender React components in testing mode. We will see both in detail below.

Let's take a look at the widely used tools for testing React apps:

Jest

In React, the most often used test runner is Jest. We can run Jest in watch mode, which can run our tests every time we save the file.

Jest is a test runner that runs all our test suites and test cases. Jest is previously introduced in testing JavaScript and React applications. We have to call Jest from the command line to run the test cases. We can have additional configurations for Jest custom setup.

Installation

Jest provides the configuration file to mention the additional configurations. We provide the file path in the package, and the JSON file is below:

Let us create a jest.config.json file in the root folder and sum the script in the package.json file to run our tests:

Let us create a jest.config.json file in the root folder and sum the script in the package.json file to run our tests:

Enzyme

The Enzyme came into the field in December 2015. It is an addition to react, simplifying the output testing in React components.

The Enzyme is a library used with the Jest in so many test libraries, and it is used to render components and traverse the DOM.

If we build a React app, Jest and Enzyme are the best combinations for testing React apps.

Jest is a test runner which is mainly used to execute the test cases with assertions. And, at the same, Enzyme is a library that is used with Jest library, that provides the rendering techniques like (shallow, mount, etc.) for React components and traverses the rendered output of the DOM.

Let's look at the enzyme setup:

Installation

Enzymes provide the adapters to work with many versions of React.So, install the adapter in theReact. Next, we are installing React16below.

Now, youhave to configure the Enzyme in the adapterto install in prank test environment.

Let's create jest.setup.js and add the below code at the file:

You have to installed an enzyme in your environment.

It is essential to decide what is required for the test and what should be left out of it.

So that, considering the next person after you to manage those test cases, there aren't a lot of unnecessary test and snapshot files left behind.

For each component for unit testing, start with small and stateless components and then move on to rigid components. So that if any complex reacts component includes another minor component already tested, that will make the process easier.

However, in thetest-driven development (TDD) process, you should first decide and write test cases that initially fail and eventually develop the functionality of the test cases that will pass.

Consider a small example to understand:

1.

2.

A Display Name component that receives a Name property as props and renders it.

The User component in the text input as the Name property validates the username for setting the error if an error is found.

We have exported two components and the validation function use in our further tests.

Unit testing the above example:

There aretwo main approaches to test the React components:

  • Snapshot testing
  • Logical/functional testing

1. Snapshot Testing

Snapshot Test generates a snapshot of the component in the current state and stores it in a folder named "__snapshots__."when you run the test.

So, next time we change the component or modify it to rerun the test;

A new snapshot is taken If it fails, which is clearly shows the difference between snapshots provided by the output of the component. If a test fails, we can either accept or reject the change and modify the component accordingly.

How is Snapshot Testing done?

Previously, we need to install the react-test-rendererutility to render the component atthe test.

Let's implement first snapshot by writing the below test case in file named UserName.spec.js:

Previously, we rendered the component displayName,converted it to JSON, and checked if it matched the previous snapshot. Let's run the test by the "npm run test" command on cmd and see.

For the first time, if you run the test, it generates a snapshot of the components' output and store it in a"__snapshots__" folder. Wesee what kind of structure it stores.

Now, Replace Display Name component and run the test again:


Unit Testing in React

We can see that it shows the changes in the component, and the test fails because it cannot match the last snapshot.

Here is an implementation changeto fix it.You need to update the snapshot it represents a bug is found in the component to fix it. We can update the snapshot by using the "-u" option.

Similarly, we add a snapshot test for the parent component.

2. Logical/Functional Testing

We can add some test cases and more tests in our code for testing the validation function.

We have added two test cases here:

  • It checks if any error message will send if the user passes any number of inputsofthe name.
  • It checks the error message if it reactswith false where input box is empty at the name property.

So,it covers the possible outcomes where the application has crashed in logic that we have forgotten to handle at the development time.

Now, we can see the below-given output if we run the tests.

Unit Testing in React

If the validation fails, the running tests will inform you; all tests will pass. Keeping the logic separate helps a lot in complex code to be tested in possible cases and seems like cleaner way to understand the code.

Reaction test library

Unlike Enzyme, react-testing-library focuses on the user behavior rather than the implementation.

The focus is on checking for correct output for a set of props, by using the react test library which is writing end-to-end tests for the components in Enzyme:

If you're not sure what you have to test,test what you expect the component to render.

Test all the different states of this component(s). If you expect different things to be rendered based on the props passed in, render the external component with different props and make the appropriate assertions.

For example, when you click or hover a button test, you have something to happen.

If you are providing a custom button component and pass a color prop with a value of red, then you can test it, and it give you the confidence that the component meets the design requirements.

Conclusion

It is very important to write unit tests, which is the simplest type of tests, and project to increase confidence and the code correctness. We have to aim for a higher percentage of code coverage to make it the part of workflow to write the unit test cases.


Next TopicCarousel in React





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA