Testing React Applications with Jest

Learn via video courses
Topics Covered

Overview

ReactJs is used by multiple developers to create different types of applications, but to make a react application more robust and sustainable in the production environment or for a business, we must test our application. Testing is an important aspect of software development and helps to improve the quality of the application.

Introduction to Testing

  • Testing is a process done to check the proper working of the application and to improve the robustness and efficiency of the application.
  • The main purpose of testing an application is to identify and rectify errors.
  • Testing is done either manually or using any automation software.
  • Testing also focuses on checking if the previously fixed bugs don't appear again, a term called regression.
  • React applications are tested by checking the rendering and user interactions of the application.

Software testing is usually a part of the software development lifecycle and has many many principles. Read the detailed explanation on software testing

Testing in react can be based on asserting the output of rendering component trees or performing end-to-end checking by running the complete application.

Types of Testing in React

There are multiple types of testing followed by different organizations. Let us learn about some of the important types of testing that will be useful for testing react applications,

Unit Test

In unit testing, a small portion of the application or a unit will be tested. A unit can be used to represent a small piece of code, function, method, property, or object. The testing is either state-based in which the state of the output is checked or the testing is interaction-based which checks for the events that occur when the user interacts with the application. A unit tester isolates a logical part of the program and tests it. In many places, unit tests are done along with programming by the developer. There are three techniques used in unit testing,

  • The testing done for user interfaces, input, and output events is called Black Box Testing.
  • The internal design and functional code are tested using the White Box Testing. In this type of testing, input is given to a function expecting a specified output.
  • Test cases and code performance of the application are evaluated using the Gray Box Testing method.

You can read multiple examples regarding unit testing in Unit Testing.

Component Test

A specific part of the application is tested individually in component testing. It can also be called module testing. Component testing is performed to check the input and output, usability, and behavior of a component. Stub and Driver are usually used in component testing for components that depend on other components. Consider the components A and B. If component A depends on component B, then the stub can be called from component A to access component B and we can use a driver on component B to call component A. Component testing is mostly done by a tester. It is a type of Black box testing.

NOTE : When a tester doesn't know the functionality of the software and performs testing based on test cases or internal knowledge, it is called Black Box testing. Whereas White Box testing such as unit testing is used to check the internal structure and design of the application.

Snapshot Test

Snapshot testing is done by comparing the output with the outputs of the previous same type of input which had a successful output. This method prevents the problem of regression. In web applications, snapshot testing checks if the layout of the application doesn't change unexpectedly. It captures the state of the application as an image at a time and uses that image to compare the state of the application. Jest provides features to implement this testing into our testing code.

A disadvantage in snapshot testing is that it only checks if the output matches the previous output and gives no assertion on whether the output is right or wrong.

Multiple philosophies and paradigms are around the testing of applications. You can learn more about the types of testing an application in Types of software testing.

Advantages of Testing

  • Testing helps to create a quality and robust application.
  • Testing can reduce the maintenance cost as most of the bugs will be resolved during the testing of an application.
  • Testing helps to create an error-free application which increases the trust of the customer and also provides customer satisfaction.
  • Security testing provides significant importance for business applications, as any security error in an application may cause a loss of money.
  • Testing speeds up the development process as developers will never have to worry about the bugs that may occur after development.
  • Testing failure perspective helps improves the recovery time of the application in case of failure.
  • Testing helps to deliver a reliable application by detecting errors in earlier stages and providing fixes for them.

Disadvantages of Testing

  • Testing of an application can be time-consuming and need more resources.
  • It may increase the cost of the total project as more money should be invested in tools and the workforce.
  • The number of members in a team will increase due to testers and high experience is needed for testing an application.
  • Increase the overall duration of sprints in the software development lifecycle.
  • The best testing techniques have to be known for testing different types of software.

What is Jest?

Jest react is a testing framework used for testing javascript and typescript that is simple to use and supports testing of frontend frameworks like React, Angular, Vue, etc...

  • There are no configurations needed to test with jest. Jest can perform snapshot-based testing.
  • Running jest tests can be parallelized by running them on their processes, which provides maximum performance.
  • Code coverage information can be easily collected using jest tests.
  • Jest provides a custom resolver for resolving imports in a file and we can use this feature to mock a file out of the test scope.
  • Jest has great documentation and learning resources.

NOTE : Code coverage is a metric that is used to track the percentage of files or the program that has been tested. Mocking is a technique that uses a known object to replace the dependencies of a component to test a single component.

Setup

The best way to set up a testing environment for jest is to install the required packages for Jest in the react environment.

Setup with Create React App

Jest react prefers using the create react app for creating a react application, as it has good compatibility with jest.

The following command can be used to create a new react application,

The name_of_app is the name of the folder in which a standard react application will be created. After running this command, you can see a new folder named name_of_app. We can navigate to this folder using the cd command,

This folder has the files for react application. To perform jest testing in react, we need to add the testing packages to our project. The following commands use the npm and yarn package managers to install the jest packages,

The --save-dev in npm and the --dev in yarn commands are used to save the package as a development dependency. Jest is a testing library and needs only for testing applications and provides no use in a production environment. Therefore, jest react is installed as a development dependency. Now, we are ready to test our application.

Setup without Create React App

This case is for applications that are created with other bundlers like next or gatsby instead of creating react apps to perform jest testing react. Multiple packages have to be installed to run jest test in react applications created without using create react app,

  • Babel is a tool used to convert ECMAScript 2015+ syntax of javascript to browser supported version of javascript and babel-jest is used to support babel for jest testing react.
  • Plugins in babel are used to make automatic code transformations and the @babel/preset-env package is used to create a list of plugins based on the syntax mappings of the target environment specified in the babel.config.js file.
  • Preset are sharable configurations for babel. The @babel/preset-react package has multiple plugin configurations.

Process of Running a Test with Jest

Before starting to test our application with jest, we need to understand the basic usage of Jest react.

  • Jest testing react files are created inside the __test__ folder in the src folder of our react application and is accessed by jest.
  • Jest react will look for files with the suffix .test.js, .js, and .spec.js.

There are no configurations needed for running jest, but if you want to add any configurations, we can do that in the jest.config.js file. The basic structure of the file is,

Finally, we will need a simple understanding of the functions provided by jest to test applications.

Explanation

The test() method is used to run a test using jest. It can also be called with the alias it(). The method has a name and the function to be invoked along with the time the function has to run. The syntax of the function is,

Explanation

The expect(value) method is used to get the output from the test and we can use matcher methods with the expect() method to check if the output and value match. Let us see a few examples of matcher methods like toBe() and toEquals(). The toBe() method is used to compare primitive values and uses the Object.is method to compare values. A simple syntactical example is,

Explanation

The toEqual is used for comparing user-defined objects and other objects. This method compares the properties of the object recursively.

Creating A Test File

If you have created your react application with create react app, you can find the App.test.js file in the src folder. If there is no such file, create a file with the name App.test.js in the src folder.

Now, we can modify our App.js file with some of the following simple code that will fetch a list of data from a backend or an API and renders the data in the frontend, instead of the default template.

Then we can modify the App.test.js file to take a snapshot and test it using jest react. Code

Explanation

  • When the test is run for the first time, a snapshot is created in the src/__snapshot__ folder. For consequent tests, jest react will use this snapshot to compare the current state of the application.
  • The Renders without crashing is the name of the test.
  • The toMatchSnapshot matcher function is used to compare the current snapshot with the previous snapshot.

We can run the test using the following command,

The snapshot for our application is like this,

After running the test, we get the following output if it is the first snapshot test or the current snapshot matches the previous snapshot,

The above test returns a successful output. Now, let us just change the sentence Testing is fun with Jest. to Testing is fun with. in our App.js file.

When we run our test again using the npm test command, we can get the following output showing that the test done by jest react has failed and what changes have been made to the current snapshot in comparison with the previous snapshot.

Skipping Or Isolating A Test

When we want to suspend or skip a particular test, we can use the test.skip(name, function) function to skip a test from execution. The following example skips the first test and executes only the second test,

The test.skip() function can also be called with an alias such as xit(), xtest(), and it.skip().

When we run the test, we can get the information that a test has been skipped,

NOTE : We can also use the test.only() function to run a single test in a file and ignore all other tests in that file.

Mocking Function

Mocking can be used to check the working of a function or module that uses an external dependency. A mock is a replication created to replace the original functionality of the external dependency.

Let us create a mock to replace the fetch() function which gets a list of data from an external backend that is rendered in the website. Create a folder named Mock in src and create a fetchMock.js file inside the Mock folder.

Conclusion

  • Testing is a process performed to check the proper working and efficiency of any application.
  • There are different types of testing for different situations.
  • Testing has a lot of advantages that improve the quality of the applications compared to its disadvantages.
  • Jest is a javascript testing library that provides compatibility to perform react tests.
  • Jest is highly compatible with react create app bundler.
  • Jest react provides test() function to craete test and mactheres and except() fucntion to evaluate tests.
  • We can skip a test or execute only a single test using the test. skip() and test.only() functions respectively.
  • Mocks are used to implement functionality that is provided by external dependencies for testing an application.