Setting up unit testing for your Node.js APIs is essential for ensuring code quality and reliability. This tutorial provides a step-by-step guide to help you configure JavaScript unit testing using popular tools like Jest and Supertest.

Prerequisites

  • Node.js installed on your machine
  • Basic knowledge of JavaScript and Node.js
  • Existing Node.js API project or a new one to test

Step 1: Initialize Your Project

Open your terminal and navigate to your project directory. Run the following command to initialize a new Node.js project:

npm init -y

Step 2: Install Testing Dependencies

Install Jest and Supertest, which are popular tools for testing Node.js APIs:

npm install --save-dev jest supertest

Step 3: Configure Jest

Add the following to your package.json to set Jest as your test runner:

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

Step 4: Create a Sample API

If you don't have an API yet, create a simple one for testing. For example, create a file named app.js:

const express = require('express');

const app = express();

app.get('/api/hello', (req, res) => {

  res.json({ message: 'Hello, world!' });

});

module.exports = app;

Step 5: Write a Test

Create a new file named app.test.js and add the following test code:

const request = require('supertest');

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

describe('GET /api/hello', () => {

  test('responds with a message', async () => {

    const response = await request(app).get('/api/hello');

    expect(response.statusCode).toBe(200);

    expect(response.body).toEqual({ message: 'Hello, world!' });

  });

});

Step 6: Run the Tests

Execute the following command in your terminal to run the tests:

npm test

Conclusion

By following these steps, you can set up a robust testing environment for your Node.js APIs. Regular testing helps catch bugs early and ensures your API remains reliable as it evolves.