Testing JavaScript code with Jest

In this post, we will get into the art of testing JavaScript code with Jest. There are many ways to test your code and many frameworks and tools to help you with it. In this specific post, we will be exploring Jest.

Jest is a delightful JavaScript Testing Framework with a focus on simplicity. Jestjs.io

Why is testing useful

Testing is still a subject that causes controversy among product managers and developers. However, testing is without a doubt a very important part of the software development cycle. There’s nothing worse than delivering work to a customer which immediately breaks upon the first test.

You should look at testing as being the friend that keeps you from looking stupid.

Without testing, you could potentially waste a lot of time on broken features which would’ve worked if you’d only tested it beforehand. Besides this, testing is also a measurement to keep you from writing bad code. When a test fails it means the expected and the actual outcome didn’t match. Most of the time, this is caused by a developer oversight.

Installing Jest into our project

We’ve rambled enough about why testing is important. Let’s get started with installing Jest into our project now.

First up, create a new directory somewhere on your computer called obz_jest. Open this directory into an IDE (Integrated development environment — Your code editor) of your choice. We use Visual Studio Code.

Open a terminal instance inside the obz_jest directory and type the following command:

$ npm init -y

Note: this command initializes our npm project and automatically takes all the default options

Next, we need to install Jest into our project. We can install Jest with the following command:

$ npm install --save-dev jest

Note: we use –save-dev since testing is something we want to enable in development environments only. For production environments, we want as little overhead as possible.

Writing our first basic test

We will start by writing a very basic test to get the hang of Jest. After that, we will move on to some more detailed tests.

Create a file called sum.js inside your obz_jest directory. Add the following content to sum.js

function sum(a, b) {
    return a +b;
}
module.exports = sum;

This file contains a single function that returns the sum of two passed numbers. One thing to note is the module.exports = sum; line. This line enables us to import this function from another file.

Now, we will make our test file. Create another file called sum.test.js and add the following content:

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

test('adds 1 + 2 to equal 3', () => {
    expect(sum(1, 2)).toBe(3);
});

Inside this file, we have written our very first test. We import the sum function we created in the sum.js file. The next line is our test case. We want to check if 1 + 2 equals 3. This is why we expect the result of sum(1, 2) to be 3. See how Jest is looking fairly similar to English? We can use that to our benefit.

Now that we have both our logic and our test file created, we need a way to run the test we just made. Inside your package.json add the following section

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

Open a terminal inside the obz_jest directory and execute the following command:

$ npm run test

If you’ve followed along well, your console should show the following:

> [email protected] test
> jest

 PASS  ./sum.test.js
  √ adds 1 + 2 to equal 3 (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.347 s
Ran all test suites.

We’ve successfully created and ran our very first test using Jest!

Testing code through mocking

Usually, when working on JavaScript projects, you’ll request data from something which is called an API. This API usually asynchronously returns the response which contains your data.

Install Axios with the following command:

$ npm install axios

Next, create a file called dogs.js with the following content:

const axios = require('axios');

module.exports = class Dogs {
    static get() {
        return axios.get('https://dog.ceo/api/breeds/image/random');
    }
}

Now, create a dogs.test.js file with the following content:

const axios = require('axios');
const Dogs = require('./dogs');

jest.mock('axios');

test('should fetch a random dog', () => {
    const resp = {
        "message": "https://images.dog.ceo/breeds/weimaraner/n02092339_7224.jpg",
        "status": "success"
    };    
    axios.get.mockResolvedValue(resp);
    return Dogs.get().then(dog => {
        expect(dog.message).toMatch('images.dog.ceo');
        expect(dog.status).toBe('success');
    })
});

This should give you the following output when you run your tests

> [email protected] test
> jest

 PASS  ./dogs.test.js
 PASS  ./sum.test.js

Test Suites: 2 passed, 2 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.486 s, estimated 1 s
Ran all test suites.

We’ve now created a test that tests API data. See how easy testing is? The benefits you gain from testing way outweigh the hassle to set it up. We hope you now have a basic understanding of how to get started with testing JavaScript code with Jest

Leave a Reply

Your email address will not be published. Required fields are marked *