Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Documentation and Testing

Testing REST APIs

Learn how to test a REST API: what to assert, test isolation, table-driven tests, authentication and error cases, plus a runnable test runner in Node.js.

An API is a contract with strangers: other teams, partners, mobile apps you cannot update. Automated tests are how you keep that contract when the code changes. A good API test suite catches a renamed field, a missing 401, a broken Location header or a validation rule that quietly stopped working, before your clients do.

This lesson shows what to test, how to structure tests so they stay fast and independent, and how to cover authentication, validation and failure cases. The examples use a tiny home-made test runner on top of node:assert, so everything runs here; the same ideas apply to node:test, Jest, Vitest, Pest, pytest or JUnit.

What to assert

Status code 201, 404, 422, 401.
Headers Location, Content-Type, caching.
Body shape Fields and types, not just values.
Side effects Was the data really saved?

Test the contract, not the implementation.

1 / 2

The anatomy of an API test

Every API test has three steps, often called arrange, act, assert:

  1. Arrange: start from a known state (empty database, a user with a token).
  2. Act: send one HTTP request.
  3. Assert: check the status code, relevant headers, the response body, and sometimes the data left behind.

Test behavior visible to clients. Do not assert on internal function calls. If you refactor the code and the responses stay identical, no test should fail.

What to cover for each endpoint

Category Example for POST /notes
Happy path Valid body returns 201, Location, the created note
Validation Missing title returns 422 with a field error
Authentication No token returns 401; invalid token returns 401
Authorization Another user's note returns 404 or 403 (BOLA)
Not found Unknown ID returns 404
Idempotency and conflicts Repeated PUT gives the same result; stale If-Match gives 412
Edge cases Empty list, maximum page size, unicode, very long strings
Error format Errors use the documented JSON shape and no stack traces

A runnable example

The program below contains a small notes API (with a bearer-token check) and a test suite that exercises it over real HTTP on a loopback port. Each test creates its own server and data, so no test depends on another and the order does not matter.

Node.js A test suite for a notes API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Seven tests pass, and the last one fails on purpose so you can see what a failure report looks like. A good failure message names the endpoint and the expectation.

Test isolation and data

  • Fresh state for every test. Create a new database (or roll back a transaction) per test. Shared state makes tests pass or fail depending on order.
  • Factories build valid records with sensible defaults so each test only states what matters to it.
  • Never test against production. Use a local or CI database, ideally the same engine as production.
  • Control time and randomness. Inject a clock and seeds. A test about token expiry should move a fake clock, not call sleep.
  • Do not call real third parties; replace payment, email and SMS providers with fakes (Contract Testing and Mocking).

Table-driven tests

When many cases differ only by input and expected output, put them in a table. Adding a case costs one line, and the table doubles as documentation.

Node.js Table-driven validation tests

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Tools you will meet

JavaScript
// node:test, built into Node (read-only example: it prints timings, so we use our own runner above)
import { test } from 'node:test';
import assert from 'node:assert/strict';

test('GET /health returns ok', async () => {
  const res = await fetch('http://localhost:3000/health');
  assert.equal(res.status, 200);
});
Tool Use
node:test, Jest, Vitest Test runners for JavaScript
Supertest or app.inject() Call an app without opening a real port
Postman and Newman, Bruno, curl scripts Exploratory and collection-based checks
Pact Consumer-driven contract tests
k6, Artillery, wrk Load and performance tests
OWASP ZAP, Schemathesis Security scans and property-based API fuzzing from an OpenAPI spec

Also test non-functional behavior: response time under load, rate limit headers, large payload rejection and graceful handling of a down database. Run the suite in CI on every pull request, and keep it fast (minutes, not hours) so people keep running it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What should an API test mainly check?

    Tests of the contract survive refactors, because they only fail when client-visible behavior changes.
  2. 2. Why create fresh data and a fresh server for each test?

    Independent tests are reliable and can run in any order or in parallel.
  3. 3. Which cases belong in an API test suite besides the happy path?

    Most bugs and security issues hide in the failure paths, so those need tests too.
  4. 4. When is a table-driven test a good fit?

    A table keeps the logic in one place and makes adding a case a one-line change.
  5. 5. How should a test cover token expiry?

    A controllable clock keeps tests fast and deterministic.

Summary

  • Each test arranges state, sends a request and asserts status, headers, body and side effects.
  • Cover success, validation, authentication, authorization, not-found, conflicts and edge cases for every endpoint.
  • Keep tests isolated with fresh data, factories, fake clocks and fake third parties.
  • Use table-driven tests for many similar cases.
  • Add contract, load and security tests, and run everything in CI.

Next: Contract Testing and Mock Servers