Writing Node.js Tests With Supertest and Mocha

Writing Node.js Tests With Supertest and Mocha
Photo by Mika Baumeister / Unsplash

Supertest is a library that can be used to write tests for HTTP servers in Node.js. It provides a simple and intuitive API for making HTTP requests and asserting the responses returned by the server.

To use Supertest, you will first need to install it as a dependency in your project. You can do this by running the following command in your terminal:

npm install supertest

Once Supertest is installed, you can use it to write tests for your HTTP server. Here is an example of a simple test that sends a GET request to the server and asserts that the response has a particular status code:

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

describe('GET /', () => {
  it('should return 200', (done) => {
    request(app)
      .get('/')
      .expect(200, done);
  });
});

In this example, we use Supertest's request function to make a GET request to the server, and then use the expect function to assert that the response has a status code of 200.

You can then run your tests using a command line tool like Mocha, which is a popular testing framework for Node.js. To install Mocha, run the following command:

npm install -g mocha

With Mocha installed, you can run your tests by using the mocha command in your terminal, followed by the path to your test file or files:

mocha test/my-test.js

This will run the tests in the specified file and display the results in the terminal. You can also use other command line options, such as --reporter or --timeout, to customize the behavior of Mocha.

For more information about using Supertest to write tests for HTTP servers in Node.js, you can consult the documentation for the library: https://www.npmjs.com/package/supertest