DEV Community

Cover image for How to Use Jest to Quickly Test Your JavaScript Applications
Kyle Petersen
Kyle Petersen

Posted on • Edited on

How to Use Jest to Quickly Test Your JavaScript Applications

Introduction

Jest is an extremely popular unit testing framework for JavaScript and is even the default unit testing packing for many of the largest frameworks and libraries such as React. Its popularity can mainly be boiled down to its absolute simplicity to implement which makes it perfect for vanilla JavaScript projects.

Install Node.js

In order to run Jest, you are first going to need to have Node.js. To do this, navigate here and select your appropriate operating system.

Initialize Our directory

For this example, I'm going to create a completely empty directory/folder named jest_practice. Now we are going to cd into our new project and within our terminal, we are going to initialize Node Package Manager with npm init.

Once you hit enter, you will be prompted to enter a bunch of information that will be used to create your Package.json file. For right now we can just use the defaults by leaving every option blank.

Alt Text

Now a file should have appeared within your project named package.json which should by default, look like this.

{
  "name": "jest_practice",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}
Enter fullscreen mode Exit fullscreen mode

After Node Package Manager is initialized we need to install Jest as a node module within the project. To do this we just need to run the command npm i jest from within our terminal.

After a short download, a new folder named node_modules should have appeared within our project as well as a file named package-lock.json.

The last step of initialization we are going to need to do is make a small change to our package.json file. On line 7 where it currently says "test": "echo \"Error: no test specified\" && exit 1" we are going to change it to test": "jest". In the end, our package.json file should look like this.

{
  "name": "jest_practice",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "jest"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jest": "^26.6.3"
  }
}

Enter fullscreen mode Exit fullscreen mode

Create Our Files

As an example for Jest, we are going to test a simple two sum problem with Jest to make sure it is working properly. From our main directory, we are going to create the file TwoSum.js and TwoSum.test.js. Once these two files are created we are going to first jump into our TwoSum.js file.

Editing our TwoSum.js File

From within our file, we are going to create a JavaScript function just like any other and name it twoSum. For simplicity's sake, I am going to go ahead and fill in the solution to the problem within the function below so we can immediately jump to testing it.

function twoSum(nums, target) {
    const map = {};
    for (let i = 0; i < nums.length; i++) {
      const another = target - nums[i];

      if (another in map) {
        return [map[another], i];
      }
      map[nums[i]] = i;
    }
    return null;
}
Enter fullscreen mode Exit fullscreen mode

The last only other thing we need to do tho this file is to export this function by writing module.exports = twoSum; right below it.

function twoSum(nums, target) {
    const map = {};
    for (let i = 0; i < nums.length; i++) {
      const another = target - nums[i];

      if (another in map) {
        return [map[another], i];
      }
      map[nums[i]] = i;
    }
    return null;
}

module.exports = twoSum;
Enter fullscreen mode Exit fullscreen mode

Setting Up Our Jest Testing

Now that we have our problem finished, all we need to do is set up our tests to make sure it is working properly. To do this, navigate to the TwoSum.test.js file we had created earlier. From here, we are going to start off by creating a requiring in our finished two sum function by typing const twoSum = require(./TwoSum); on line 1.

After we have required our twoSum function, we are going to start building our test by using test(). The first parameter of the test function is going to be a message describing what specifically we are testing. In the first test, we are just going to see if one of our inputs equals an expected output so our message will me test("Given an array integers and a target, the function should return two indices such that they add up to the target."). The second parameter of the test() function will be the actual expected input and output which we will format like so.

test("Given an array integers and a target, the function should return two indices such that they add up to the target.", () => {
    expect(twoSum([2,7,11,15], 9)).toEqual([0,1])
})
Enter fullscreen mode Exit fullscreen mode

In the end, the TwoSum.test.js file should end up looking like this.

const twoSum = require('./TwoSum')

test("Given an array integers and a target, the function should return two indices such that they add up to the target.", () => {
    expect(twoSum([2,7,11,15], 9)).toEqual([0,1])
})

Enter fullscreen mode Exit fullscreen mode

Now if we run the command npm run test within our terminal we should get a passing test!

Alt Text

That's the super fast way to get Jest up and running on your project. Keep in mind though that probably going to need to test much more if we want to make sure our code is full proof and for this, Jest has a ton of different Matchers. For example, if we wanted to make sure our function returned null if there were no two indices that equaled the target we could use the matcher .toBeNull instead of .toEqual or we could even check if our function returns values greater than or less than certain values by using the .toBeGreaterThan() or .toBeLessThan(). For more details on Matchers you can reach the Jest documentation here.

Top comments (1)

Collapse
 
ky1e_s profile image
Kyle Stephens

Make Jest testing and debugging super enjoyable by installing the VS Code Jest Extension - github.com/jest-community/vscode-jest