Basic APIs Testing with JEST and SuperTest

Write API testing easily with JEST and SuperTest

Testing is a very important part of a developers' career. We often find ourselves testing our code manually, decreasing productivity and introducing ground for nasty bugs to surface. Many developers prefer to test code manually because they find it difficult to set up the test environment. Often I found myself refactoring a large part of code to make it testable.

In this article, we will see how easy it is to set up unit testing by creating a hello world API in node.js.

Creating a basic server

Let's create a folder and init a node.js project.

$> cd hello-world-test
$> npm init --yes

This will create a package.json file to track project dependencies.

We need to install express. If you don't know, express is a web framework. And we will use it to create our hello world API

$> npm i express

Now let's create our main entry point file. Create a file server.js

const express = require('express')
const app = express()

// start the server on port 3000
app.listen(3000)

Let's create our hello world api. Edit your server.js file to match following -

const express = require('express')
const app = express()

// hello world api
app.get('/', (req, res) => {
  res.send({ message: 'hello world' })
})

// start the server on port 3000
app.listen(3000, () => {
  console.log('server started')
})

Let's start our server and see

$> node server.js

You should see server started printed in the console. We are good to go.

Testing our API

To test our hello world API, we need to make few changes to the server.

First, let's create a new file named app.js. This file will export our express app but won't start the server. This is required for the supertest library.

app.js

const express = require('express')
const app = express()

// hello world api
app.get('/', (req, res) => {
  res.send({ message: 'hello world' })
})

// export our express app
module.exports = app;

and let's modify our server.js file to use the express app instance from app.js.

server.js

const app = require('./app');
// start the server on port 3000
app.listen(3000, () => {
  console.log('server started')
})

Now we're ready to set up our API testing. We need our testing and assertion libraries.

Let's install

$> npm install -D jest supertest

Let's create a folder tests and create a file hello-world.spec.ts, and add the following.

const request = require('supertest');
const app = require("../app");


describe("test hello-world", () => {
  it("should return hello world", (done) => {
    request(app)
      .get("/")
      .expect("Content-Type", /json/)
      .expect(200)
      .then((response) => {
        expect(response.body.message).toBe("hello world");
        done();
      })
      .catch((e) => done(e));
  });
});

Finally, let's run our test and see it passing -

$> npx jest

If everything worked as expected, you should see below.

 PASS  tests/hello-world.spec.js
  test hello-world
    ✓ should return hello world (18 ms)

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

This means we have created an endpoint and ran a test to verify the response of the endpoint.

If you are still struggling you can see and compare your code from the source code found here.

And you can also connect me on Twitter.

I hope you find this article helpful. Let me know your suggestions in the comment.