An Ultimate Guide To Install, Set Up, and Use The Jest Framework

Jest Installation Guide

Jest is one of the most widely used and truly effective testing frameworks used for testing JavaScript-based applications. Our previous article on a detailed introduction to Jest might have made you familiar with different aspects of this amazing tool. Now, here we are going to focus on how you can proceed with installing, setting up, and starting to use it.

How To Decide What To Test?

Before moving on to the larger steps, you must have the fundamentals cleared to decide what you need to test. Now, the easiest decision to solve this conflict is that you should test every bit of the application. That means there should be dedicated test cases for every page as well as everything that the users interact with.

However, there are numerous units of code like small software modules and functions that must be thoroughly tested before making them available to users. The two most common sceneries where you need to decide about your tests are -

  • You inherit legacy code. Those codes are the base code or source code that already has predefined tests for them or has already gone through tests. Hence, either you don’t need to test them again or can run the predefined tests.
  • You had to suddenly implement a new functionality that was not planned in detail, and you must focus on carefully testing it.

For both the cases mentioned above, you must follow a strategic flow of steps to ensure that your entire code is tested. So, let’s check out the steps that you need to follow.

  • First of all, the required function should be imported for a particular test.
  • Now, you need to pass the necessary input into the chosen function.
  • In this step, the body of the function should be defined so that it produces the desired output after it is executed.
  • Finally, remember to check if the function is working properly so that it produces the desired output.

How To Install Jest?

Well, the installation of Jest is not a very complicated task but, there are a few prerequisites before getting started with that. So, let’s take an in-depth look at the crucial libraries and packages required for installing Jest.

1. Node Package Manager (npm) and NodeJS: You can directly install NodeJS by using the windows installer binary from the org website or by using the npm manager. The node package manager is an open-source software library consisting of more than 8 lakhs code packages, or a command-line tool that is generally used to update, install or uninstall various nodeJS packages in web-based or mobile applications.
You need to navigate the npm-command line tool and install the latest version. For that, you can apply the command as mentioned below -

$ npm init -y

2. Selenium Web Driver: There is rarely anyone who is interested in test automation but has not heard about Selenium Web Driver. We also have previously published a detailed article on codeless Selenium test automation to guide you through the process. Now, let’s see why Selenium Web Driver is significant here.
If you want to run or implement cross-browser tests, the Selenium web driver is a prime requirement for you. By using it, you can use any programming language that is suitable for you to create various test scripts. While automating mobile or any web-based application testing, the Selenium web driver allows you to verify whether the application performs expectedly or not. Selenium web driver is a reliance for the jest module that is installed in the root directory.

To download the latest version of selenium Web Driver, use the below-mentioned command line.

$ npm install selenium-webdriver

Now, you can install the jest module using npm by using the following command in the command line.

$ npm install --save-dev Jest

To run commands in the command line, the Java -SDK jest keyword can be used. Now, before moving on with the jest framework installation process, make sure to check whether your system is already done with the installation process of Java Development Kit and configure the system with the Java environment. That’s because Jest is a Selenium test framework, and Selenium is built on Java itself.

The jest module can be globally installed using the ‘-g’ flag which can also be used along with the npm command. It will look like this -

$ npm install -g jest

The npm command that is used to install the suitable driver required to trigger the browser and to place the executable inside the root directory is -

$ npm install -g chromedriver

How To Start Using Jest?

As you got to know how to install Jest, it’s time for you to focus on how to start using it. That’s why we have jotted down the steps required to set up and use Jest.

1. Create A Sample Project

This is the step where you will create an npm-based project to store the production code and test code. For that, create a folder along with accessing it.

mkdir learning-jest
cd learning-jest

Then running the command “npm init -y” will create a project that has a package.json file containing the following -

{
  "name": "learning-jest",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Now, you need to create an index.js file and paste the following into it.

function fizz_buzz(numbers) {
    let result = []
   
    for (number of numbers) {
        if (number % 15 === 0) {
            result.push('fizzbuzz')
        } else if (number % 3 === 0) {
            result.push('fizz')
        } else if (number % 5 === 0) {
            result.push('buzz')
        } else {
            result.push(number)
        }
    }
   
    return result.join(', ')
}

module.exports = fizz_buzz;

The function included in the above-mentioned code is the solution for the famous FizzBuzz programming interview question.

Source of example: https://www.testim.io/blog/jest-testing-a-helpful-introductory-tutorial/

2. Add Jest To The Project

Jest can be added as a development dependency to the project by using the following command -

npm install --save-dev jest

Now, change the following part in your package.json file. The change will look like from this -

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },

To this -

"scripts": {
    "test": "jest"
  },

3. Write Your First Test

Create a new file called index.test.js, and paste the following content on it -

const fizz_buzz = require('./index');

describe("FizzBuzz", () => {
    test('[3] should result in "fizz"', () => {
      expect(fizz_buzz([3])).toBe('fizz');
    });

    test('[5] should result in "buzz"', () => {
      expect(fizz_buzz([5])).toBe('buzz');
    });

    test('[15] should result in "fizzbuzz"', () => {
      expect(fizz_buzz([15])).toBe('fizzbuzz');
    });

    test('[1,2,3] should result in "1, 2, fizz"', () => {
      expect(fizz_buzz([3])).toBe('fizz');
    });

});

The above test code tries to verify the following -

  • Passing an array that contains 3 should result in “fizz”
  • An array that contains 5 should result in “buzz”
  • An array that contains 15 should result in “fizzbuzz”
  • Passing an array that contains 1, 2, and 3 should result in “1, 2, fizz”

Source of code: https://www.testim.io/blog/jest-testing-a-helpful-introductory-tutorial/

4. Run Your First Test

Here comes the final step where you are going to run the first test that you just created, and you can do that by simply running the “npm test” command.

In the result window, you will be able to see all passed test suites and the total time taken in executing the tests. And, if any test fails, it will also be shown along with the errors that caused the failure.

Jest Vocabulary

Well, by vocabulary, we mean the most commonly used terms in Jest operations. And, those terms that are also popular in operations involving other testing tools are mock and spy. Now, let’s check them out briefly.

Mock

In terms of Jest, mock is something that captures calls to a function and erases the actual implementation of a function. The best part about using mock is that we have complete control over the value a function returns, and control whether the value becomes correct, wrong, or it causes an error.

Now, creating a mock is so easy that it just needs assigning the following snippet of code to a function or dependency -

jest.fn()

Here is a simple example of a mock. We are mocking mockFunc, calling it, and will check if the mock has been called.

const mockFunc = jest.fn();
mockFunc();
expect(mockFunc).toHaveBeenCalled();

Spy

A spy is slightly different from a mock but can be described as an extension of it. To explain this fact, it can be said that a spy lets you verify if a function has been called the right number of times and holds the right input parameters.

Below is an example where we are going to check if the play method of a video returns the correct result along with getting called with the right parameters. Then we spy on the play method of the video object and check if the spy is working correctly.

However, as shown in the example below, remember to restore the mock to its original implementation in the end.

const video = require('./video');

test('plays video', () => {
const spy = jest.spyOn(video, 'play');
const isPlaying = video.play();

expect(spy).toHaveBeenCalled();
expect(isPlaying).toBe(true);

spy.mockRestore();
});

Conclusion

From both our articles related to Jest, you can easily figure out how useful it is, and you can bring it to use in a pretty simple way. This article takes you on a deeply exploring journey through the steps of getting started with this amazing testing framework and becoming a true user of it. So, go through it with complete attention.

Also, as we always say, if you want to achieve good test coverage, using an efficient codeless test automation tool like Preflight is the most effective way to do that. This simple browser extension can solve all your testing needs and you don’t need to write even a single line of code to reach there. You can start becoming a fan of such a magical testing experience by booking a demo.

In addition to this, we must tell you to keep an eye on our website for the absolutely unimaginable updates coming up in our products. Also, if you love to read tech articles, you must check out our blog page.