agyanadda@gmail.com

Node.js Testing

Advanced Node.js 1 min read Updated Dec 3, 2026 Topic 27 of 30

Automated tests check your code every time you change it.

Built-in test runner

Modern Node includes node:test and node:assert — no packages needed.

  • test('name', () => { ... }) or describe / it
  • assert.equal, assert.deepEqual, assert.throws, assert.rejects
  • Run all tests with node --test

Testing an Express API

Supertest sends requests to your app without starting a real server. Export app from one file and call app.listen() in another, so tests can import the app.

Popular frameworks

  • Jest — very popular, with mocking and snapshots
  • Vitest — fast and Jest-compatible, great with Vite
  • Mocha + Chai — classic combination

What to test

  • Pure functions (calculations, validation)
  • API routes: status codes and response bodies
  • Error cases, not only the happy path

Use a separate test database and reset it between tests.

Example

Example — Unit and API tests JavaScript
// utils.js
export const gst = (amount, rate = 18) => Math.round(amount * rate) / 100;

// app.js  (export the app; start the server in server.js)
import express from 'express';
export const app = express();
app.get('/api/health', (req, res) => res.json({ status: 'ok' }));

// test/app.test.js
import { test } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { gst } from '../utils.js';
import { app } from '../app.js';

test('gst calculates 18% by default', () => {
  assert.equal(gst(1000), 180);
  assert.equal(gst(1000, 5), 50);
});

test('GET /api/health returns ok', async () => {
  const res = await request(app).get('/api/health');
  assert.equal(res.status, 200);
  assert.deepEqual(res.body, { status: 'ok' });
});

// Run: node --test

node --test finds files in the test folder and prints ✔ for each passing test, e.g. "✔ gst calculates 18% by default" and "pass 2".

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which command runs Node's built-in test runner?

Exercise 2 True / False

Supertest can test an Express app without starting a real server.

Exercise 3 Fill in the Blank

Compare objects in tests with assert.___Equal()

Frequently Asked Questions

For new projects and libraries, node:test is enough and needs no dependencies. Jest or Vitest add richer mocking, watch mode and nicer output, and are common in existing projects and frontend code.