Cheat sheet to get started with the implementation of unit tests for REST endpoints in Node.js

This blog post is a cheat sheet to get started with the initial technical implementation of unit tests for REST endpoints implemented in Node.js and is structured in following sections:

  • Short overview
  • Installation of Mocha and Supertest
  • Unit test implementation perperation on the Node.js server
  • Unit test implementation itself
  • Execute the unit test
  • Summary

Short overview

For the unit tests implementation is commonly used Mocha and for testing http endpoints it is often used in combination with Supertest.

  • “Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on GitHub.”
  • “The motivation” …for the Supertest … “module is to provide a high-level abstraction for testing HTTP, while still allowing you to drop down to the lower-level API provided by superagent.”

Here is a useful blog post How to Unit Test with NodeJS? to get started with unit tests and Node.JS

Installation of Mocha and Supertest

# global install
npm install mocha -g
# project install
npm install mocha --save-dev

# project install
npm install supertest --save-dev

Test implementation perperation on the Node.js server

We need to start and stop the server in the unit test, therefor we need to add following code to the server implementation.

const server = app.listen(port, function () {
    console.log('backend is running'); 
});

  • To access the server from the test, we need to export the server as a mudule.
// Export for test
module.exports = server;

Test implementation itself

We will test two REST endpoints / and /health. We do expect as 'Content-Type', /json/ and the return code 200 as the responses for each REST endpoint as our test result.
We setup following sequence for our unit test.

  • start the server for each run
  • stop the server after each run
  • test the route endpoint
  • test the /health endpoint

Here is the example code:

var request = require('supertest');

describe('loading express', function () {
  var server; //server

  // start the server for each run
  beforeEach(function () {   
    delete require.cache[require.resolve('../server')];
    server = require('../server');
  });

  // stop the server after each run
  afterEach(function () {
    server.close();
  });

  // test the route endpoint
  it('responds to "/" with json', function (done) {
  request(server)
    .get('/')
    .set('Accept', 'application/json')

    // verification of the return values
    .expect('Content-Type', /json/)  
    .expect(200, done) // integration
  });

  // test the /health endpoint
  it('responds to "/health" with json', function (done) {
    request(server)
      .get('/health')
      .set('Accept', 'application/json')
      // verification of the return values
      .expect('Content-Type', /json/)
      .expect(200, done)
    });
});

Execute the unit test

We need to add following entries into the package.json of the Node.js application to execute the test with mocha or npm.

...
"scripts": {
    "start": "node server.js",
    "test": "mocha"
  },
...

  • Start with mocha
mocha -R spec test/server.functionality.test.js

  • Start with npm
npm run test/server.functionality.test.js

  • Example execution result
> server@1.0.0 test
> mocha "./test/server.functionality.test.js"

  loading express
server backend is running
** 200 { message: 'server is local testing in a container' }
    ✓ responds to "/" with json
server backend is running
** 200 { message: 'server is running in example mode' }
    ✓ responds to "/health" with json


  2 passing (197ms)

Summary

I like the combination of Mocha and Supertest. It’s easy to setup and easy to use from my perspective.


Maybe this was useful for you and let’s see what’s next?

Greetings,

Thomas

#Mocha, #Supertest, #Unittest, #Nodejs, #Javascript

One thought on “Cheat sheet to get started with the implementation of unit tests for REST endpoints in Node.js

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.