Jest Testing Framework Introduction

Learn via video courses

Overview

Jest is a Javascript testing framework used for test-driven development with node.js. Jest is most popularly used for unit testing. Jest provides an easy-to-use experience out of the box and it is very user-friendly. Jest helps to write clean, simple, and understandable test cases which ensure that the tested code works as expected.

Introduction

Test Driven Development is a technique where we define the behaviour of our code before even writing the code implementation. Testing helps to reduce bugs and increases the maintainability of an application. Test Driven Development or TDD is the norm for industry standard code and it is extremely useful to get insights about our code that we wouldn't have realized otherwise. Tests help developers to realize if their applications have any unexpected behaviour or not. Tests teach us about our code and make us better at debugging.

Here are a few types of functional tests:

  • Unit Testing: The goal is to validate the behaviour of small units of code like functions and methods. Tests are performed individually on these units. For eg: Testing if a function to sum two numbers is returning the correct sum or not.
  • Integration Testing: The goal is to test multiple units of code together and check if they are working together as expected or not. For example, testing whether a service can fetch data from another service or not.
  • End-to-end Testing: The goal is to emulate actual user behaviour where the application is tested as a whole. For eg: Testing if an authentication application is correctly authenticating users or not. This is also known as System Testing.
  • Acceptance Testing: The goal is to test the functionalities of the application and if they are compliant with the business requirements or not. The software must meet the criteria laid out by the business requirements to pass acceptance testing.

Jest

What is Jest Framework?

Jest is one of the most popular JavaScript Testing frameworks. Jest is very compatible as it works with Vanilla JavaScript, Node.JS, React, Angular, TypeScript, etc and it is being used on thousands of different applications. Testers use Jest extensively for unit testing JavaScript functions. Jest ensures that a JavaScript application has working code that produces the correct output. It is also very intuitive since Jest syntax is very readable. While working with the Jest Testing Framework, we use its feature-rich API which is fast and user-friendly. Since Jest is open-source, there is excellent community support for the testing framework. This included very well-documented software specifications, regular updates, and the ability to extend Jest functionality to various applications. It was built on the concept of making testing simple and fun. Jest doesn't require any third-party tools for testing JavaScript and offers a pleasant user experience. It can be used for both front-end and back-end testing.

Jest-uses

What are the Features of Jest Framework?

  • Requires No Configuration: Jest is well-designed and user-friendly. The testers do not need to make any configurations to start working with Jest. Most JavaScript projects require zero configuration for testing with Jest. This is because Jest offers all the required configurations out of the box.
  • Application Command Line Interface: Jest offers a CLI tool that gives users more control over their tests. This tool can be used to run tests on a use-case basis directly from the command line.
  • Jest makes test cases Isolated: Jest has an isolation feature to increase the performance of the tests. Individual tests are run parallelly which achieves multi-tasking. This makes testing faster. This also means that units of code can be tested in a vacuum.
  • Asynchronous Code Testing: Since JS is an asynchronous language, the Testing Framework also needs to be able to test asynchronous pieces of code. Jest can be used to test asynchronous JS snippets like promises, callbacks, etc.
  • Snapshots: If we have worked with client-side applications before, we know that they often work with large objects. Jest allows us to easily test the properties of these large objects using Snapshots. Jest ensures that the data in these large objects have a correct value and that the data type is also correct. These snapshots can be embedded inline or stored along with the tests.
  • Helper Functions for Setup & Teardown: There can be units of code that require some functionality to run before and after the code. For eg: Connecting to a database before running the code and closing the connection to the database after the code has been executed. Jest provided helper functions to streamline this process with a few lines of code.
  • Well-Maintained API: The Jest API is not only fast but also provides a hassle-free experience. Every API endpoint is intuitive, understandable, and well-documented. There is a huge stress on making the testing process simple for users.
  • Mock Functions: Jest allows us to test the control flow of the application using mock functions which don't implement the functionality of a function but acts as a placeholder. We can track the calls to a particular function by mocking it, counting the number of constructor instances, and much more!
  • Jest Community: Jest is open-source software and it is maintained by a hard-working community. Various new features and software-specific plugins like Vscode-jest have been developed to make the testing process even easier. We can also contribute to Jest by visiting the GitHub repository. Developers can choose to only use specific parts of the Jest framework that they require while discarding unwanted features since the code is available to all.

Setup of Jest for Executing any Test/Project

Ideally, if the guidelines of Test Driven Development are being followed, then tests are meant to be written before we write our actual business logic units like functions and methods. A test describes the requirement of a code and then validates that piece of code. The process starts with writing a test that will fail. Then we write our business logic code which will pass the test. Finally, we refactor or optimize our test and code in a lifecycle behaviour.

Jest-tdd

However, there can be cases where we want to test legacy code or already existing units where testing wasn't performed initially. We can follow the following testing flow:

  1. Select the unit of code which we want to test on like a function.
  2. Identify the input to be provided to this function and the expected output.
  3. Write the test so that it passes the input to the function, catches the output from that function, and then compares it with the expected result.
  4. This is performed several times with different inputs.

Jest Installation and Configuration

Node Package Manager (NPM) and NodeJs

To install Jest Testing Framework using NPM, run the following command:

To save the Jest npm package as a dev dependency in node js we can run the following command:

Output: Jest-output

Selenium WebDriver

Selenium is a popular tool for testing in the industry and we can use this framework to perform cross-browser testing. Selenium WebDriver allows us to create language-agnostic test scripts which can also be used for automating the testing process. To install Selenium WebDriver use the following command:

Output: Jest-output-2

Here is the package.json file after installing the above dependencies:

Notice how we have changed the test script to

This will help us run the tests using the following command:

We can also use the following command to run tests:

The verbose marker allows Jest to show a detailed explanation when running tests which helps us to identify bugs easily.

Basics of Jest

We will start by creating a file with a unit of code like a function. In the following example, we have created a JS file with four functions that perform different arithmetic operations:

Filename: App.js

Note 📝: Tests should be written in separate files from our main code. A test filename must have .test.js extension. Ensure that the main code and test file are kept in the same directory.

This is how we will write a simple test for these functions: Filename: App.test.js

Here is the output we get when we run the test file using the following command:

Jest-output-3

We use the test function to test a unit of code. The first argument is the name of the function which is a string in this case. The second argument is a callback function that uses the expect function to call the unit function. We chain the expect function with the toBe function where we pass the expected output. We passed all the tests successfully in this case.

Jest Running Example

Jest Skipping Test

There is no need to run all the tests. It could be possible that we only want to test a particular unit of code. For this, we can skip tests as per our requirement. The following code snippet shows test skipping with Jest:

Here we have used test.skip and xtest to skip the tests. Here is the output for the same: Jest-output-4

Jest Parameterized Test

Jest allows us to run parameterized tests where we can pass multiple testing values to test all of them using the same testing function. Here is the code snippet for parameterized tests:

Here we are passing the testing values as an array of arrays. Here is the output when we run the above tests:

Jest-output-5

Jest Grouping Test

Jest also allows us to group similar tests in a test block using describe. Here is the snippet with the describe function:

We have grouped tests from two JS files here. The strings file is as follows: filename: strings.js

We have also added a few failing tests intentionally to the above tests. When we run the Jest tests, we get the following output: Jest-output-6

Now we have seen both passed and failed tests.

Jest Testing Axios

Let's start by installing Axios using the following command:

After Axios has been installed, let's write a simple get request using Axios. Here is the snippet: filename: Fetcher.js

Now let us write a test file for the same. Here is the snippet:

Here we expect a promise which will resolve to an object to mock the Axios functionality. Here is the output: Jest-output-7

Conclusion

  • Test Driven Development helps us to reduce bugs and increase the maintainability of our code.
  • Jest is a Javascript Testing Framework that is used for extensive unit testing for JavaScript applications.
  • Jest is intuitive,user-friendly, fast, and has a feature-rich API.
  • Features of Jest include zero-configuration, application CLI, Isolated, Snapshots, Helper Functions, etc.
  • We can use Jest on new code as well as legacy applications.
  • Jest can skip tests, run parameterized tests, and group tests together.
  • We can use mock functions in jest which will mock functionalities like fetching from an API using Axios.