Testing Node APIs: Jest, Mocha, Chai, Supertest and Mocking

Node.js and Express: Build a Back End API from Scratch · Testing, Debugging and Deployment · 8 min read · Updated

Replace what you do not own

  1. A test arranges data, runs the code and checks the result.
  2. The code receives its dependencies as arguments, so a test can pass fakes.
  3. The mock gateway returns a fixed answer and remembers how it was called.
  4. The test checks both the result and that the gateway was used correctly.

You have seen tests all through this course. This lesson gathers the ideas and shows the three tools that employers ask about: Jest, Mocha with Chai, and Supertest. Their names differ, but the structure is the same: set up some data, run the code, and check the result. A test is a small program that fails loudly when your code stops doing what you meant, so that you find out in a second on your laptop, not a week later from a customer.

What to test

  • Unit tests check one small function or class with no network and no database. They are fast, so you can have thousands.
  • Integration tests check several parts together, such as a route, the service and a test database.
  • API tests send real HTTP requests to your app and check the status and the body. Supertest does this without opening a port.
  • A good balance is many unit tests, a fair number of API tests, and a few end-to-end tests of the most important journeys, such as sign up and checkout.

The code under test

The cart module below adds up prices in cents and charges a payment gateway. The gateway is a dependency, a thing the code needs from outside. In the test we do not want to charge a real card, so we pass a replacement.

// A small module to test: it depends on a payment gateway that we replace with a mock in tests.
function totalCents(items) {
  return items.reduce((sum, item) => sum + item.priceCents * item.qty, 0);
}

async function checkout(items, gateway) {
  if (!items.length) throw new Error('Cart is empty');
  const amountCents = totalCents(items);
  const result = await gateway.charge(amountCents);
  return { amountCents, paid: result.ok };
}

module.exports = { totalCents, checkout };

Mocks and stubs

A stub is a fake that returns a fixed answer, such as a gateway that always says ok: false. A mock is a fake that also records how it was used, so you can ask afterwards: was charge called once, and with the amount 1000? The tools of each library create them for you. They work only because the code receives the gateway as an argument, which is why dependency injection in lesson 32 makes testing easy.

Jest

Jest is the most widely used test runner. It includes the test runner, the expect assertions and mocking, so one package does everything. A test is test('name', fn), tests are grouped with describe, and jest.fn() creates a mock.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Run npm install -D jest, save the module as t42-cart.cjs and the tests next to it, and run npx jest.
const { totalCents, checkout } = require('./t42-cart.cjs');

describe('totalCents', () => {
  test('adds price times quantity', () => {
    expect(totalCents([{ priceCents: 250, qty: 2 }, { priceCents: 100, qty: 1 }])).toBe(600);
  });
  test('an empty cart is zero', () => expect(totalCents([])).toBe(0));
});

describe('checkout', () => {
  test('charges the gateway with the right amount (mock)', async () => {
    const gateway = { charge: jest.fn().mockResolvedValue({ ok: true }) };
    const result = await checkout([{ priceCents: 500, qty: 2 }], gateway);
    expect(gateway.charge).toHaveBeenCalledWith(1000);
    expect(gateway.charge).toHaveBeenCalledTimes(1);
    expect(result).toEqual({ amountCents: 1000, paid: true });
  });
  test('rejects an empty cart and never calls the gateway', async () => {
    const gateway = { charge: jest.fn() };
    await expect(checkout([], gateway)).rejects.toThrow('Cart is empty');
    expect(gateway.charge).not.toHaveBeenCalled();
  });
});
Tests:       4 passed, 4 total

Mocha and Chai

Mocha is a runner that does only that job, and it pairs with an assertion library such as Chai, which reads like English: expect(result.paid).to.equal(false). For stubs and spies you add a library such as Sinon, or write a small stub by hand, as the example does. Many older codebases use Mocha, so you will meet it often.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Run npm install -D mocha chai, save the file with the extension .mjs, and run npx mocha t42-cart.mocha.test.mjs.
import { expect } from 'chai';
import { createRequire } from 'node:module';
const { totalCents, checkout } = createRequire(import.meta.url)('./t42-cart.cjs');

describe('cart with Mocha and Chai', () => {
  it('adds price times quantity', () => {
    expect(totalCents([{ priceCents: 250, qty: 2 }])).to.equal(500);
  });

  it('uses a hand-made stub for the gateway', async () => {
    const calls = [];
    const gateway = { charge: async (amount) => { calls.push(amount); return { ok: false }; } };   // a stub that always declines
    const result = await checkout([{ priceCents: 300, qty: 1 }], gateway);
    expect(result.paid).to.equal(false);
    expect(calls).to.deep.equal([300]);
  });

  it('throws for an empty cart', async () => {
    try {
      await checkout([], { charge: async () => ({ ok: true }) });
      expect.fail('should have thrown');
    } catch (error) {
      expect(error.message).to.equal('Cart is empty');
    }
  });
});
3 passing

Supertest and the built-in runner

Supertest sends requests straight into an Express app. Node 20 and later also has a built-in test runner, node:test, with mock.fn(), so you can write tests with no extra packages except Supertest. The test below creates an app that depends on a weather service, replaces the service with a mock that says it is 38 degrees, and checks the advice. It then changes the mock to 22 degrees and checks again.

// Supertest + node:test (built in, nothing extra to install except supertest).
import test, { mock } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import express from 'express';

function createApp({ weather }) {
  const app = express();
  app.get('/api/advice', async (req, res) => {
    const { tempC } = await weather.get(req.query.city);
    res.json({ advice: tempC > 30 ? 'Drink water' : 'Enjoy the day' });
  });
  return app;
}

test('a mocked dependency lets us test hot and mild days', async () => {
  const weather = { get: mock.fn(async () => ({ tempC: 38 })) };
  const app = createApp({ weather });

  assert.equal((await request(app).get('/api/advice?city=Pune')).body.advice, 'Drink water');
  assert.equal(weather.get.mock.callCount(), 1);
  assert.deepEqual(weather.get.mock.calls[0].arguments, ['Pune']);

  weather.get.mock.mockImplementation(async () => ({ tempC: 22 }));
  assert.equal((await request(app).get('/api/advice?city=Pune')).body.advice, 'Enjoy the day');
});

Run it with node --test. It passes. Notice that the test never calls the real weather service, so it is fast and does not break when the internet does.

Writing tests that help

  • Test behaviour, not implementation details. A test that breaks when you rename a variable is a burden.
  • Name tests as sentences: rejects an empty cart and never calls the gateway.
  • Cover the unhappy paths: empty input, wrong types, missing permissions, and failures of the thing you depend on.
  • Keep tests independent. One test must not need another to run first.
  • Run them on every push, as lesson 44 shows. A test that is never run protects nobody.

Your task

  1. Add a test that a gateway failure, a thrown error, makes checkout reject.
  2. Write the same cart test in the built-in node:test style.
  3. Check coverage with npx jest --coverage and add a test for a line that is not covered.

How to check it worked

  • You can explain the difference between a stub and a mock.
  • A test never calls a real payment or weather service.
  • You can say why the gateway is a parameter.

Frequently asked questions

Jest or Mocha?

Both are common. Jest is all-in-one and popular for new projects. Mocha with Chai is in many older codebases. The built-in node:test runner needs no packages.

What is the difference between a mock and a stub?

A stub returns fixed answers. A mock also records how it was called so a test can check that.

Does Supertest need the server to listen on a port?

No. You pass the Express app and it sends the request internally, which is faster and avoids port clashes.

Practise with interview questions