Debug APIs with Postman or Apifox and Automate Node.js API Tests
🎯 Introduction
By the end of this article, you will be able to inspect APIs with Postman or Apifox and verify response statuses and data with automated tests.
🛠 Debug a running endpoint manually
Run routing-server.mjs from the routing article. Create a request in Postman or Apifox, select GET, enter http://127.0.0.1:3000/users, and send it. Expect 200 and a user array.
Do not stop at “request sent.” Check the status, response headers, and body. A connection failure differs from a server-returned 404: the former may never reach the endpoint.
📋 Put parameters in the correct location
| Data to send | Tool location | Example |
|---|---|---|
| User ID | URL path | /users/7 |
| Filter criteria | Query | name=Ming |
| JSON data | Body in JSON/raw mode | name field |
| Body format | Content-Type header | application/json |
| Access credential | Authorization header | Bearer followed by an actual token |
| File | Body in form-data mode | Select a file for the file field |
To test a body, stop the routing service and run request-server.mjs from the request parsing article. Submit {"name":"Ming"} to /users and expect the same JSON. Change name to a number and expect 400.
The tool may retain old cookies, so clear them when testing unauthenticated requests. Desktop tools do not enforce browser CORS restrictions; verify cross-origin behavior in the actual page.
🧰 Request an Express app with Supertest
Supertest can request an Express app directly and assert statuses, headers, and bodies, making it suitable for API tests. Install the dependency:
npm install --save-dev supertest@7.3.1
Node.js includes the node:test runner. Create api.test.mjs and import the app from the routing article:
import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from './routing-app.mjs';
routing-app.mjs defines routes without listening on a fixed port. Supertest starts a temporary HTTP service for the test and closes it afterward.
✅ Check successful responses
Add a test:
test('returns the public user list', async () => {
const response = await request(app).get('/users').expect(200);
assert.deepEqual(response.body, { data: [{ id: 1, name: 'Ming' }] });
});
expect(200) checks the HTTP status; deepEqual checks the entire body. An assertion expresses an expectation as a check that fails the test if unmet. Returning an extra internal field such as a password also fails this body check.
🛑 Check unmatched routes
Continue with:
test('returns 404 for an unknown endpoint', async () => {
const response = await request(app).get('/missing').expect(404);
assert.equal(response.body.error, 'Endpoint not found');
});
This ensures unknown URLs are not incorrectly treated as successes. Real applications should also cover invalid parameters, missing authentication, and insufficient permissions.
🧾 Check JSON parsing failures
Import error-app.mjs from the shared exception handling article and test malformed JSON:
import { app as errorApp } from './error-app.mjs';
test('returns an explicit error code for malformed JSON', async () => {
const response = await request(errorApp).post('/users')
.set('Content-Type', 'application/json').send('{').expect(400);
assert.equal(response.body.error.code, 'INVALID_JSON');
});
The request sends incomplete JSON. Parsing middleware rejects it, and error middleware returns 400. The test verifies the caller-visible result.
🚀 Run the tests and confirm they detect problems
Run this in the example directory:
node --test api.test.mjs
All three tests should pass. Temporarily change the user list status to 201 and rerun: the first test should fail. Restore the code afterward. This confirms the test checks the expected status.
Database tests should use a separate test database and disposable data. For email, payments, and other external operations, use provider test environments or controlled substitutes rather than contacting real users. Failed tests produce a nonzero exit code so automated release workflows can stop.
❓ Questions and Answers
Q1: Must tests occupy port 3000?
No. Supertest can use a temporary port when requesting the exported app.
Q2: Is checking that a request did not throw enough?
No. Check the status and body too; HTTP failure responses can reach clients normally.
Q3: Do passing tests guarantee a working deployment?
Deployment configuration, database connections, and reverse proxies still need checking. Tests cover only the scenarios they define.
🧪 Practice
Add a /health test checking 200 and status equal to ok. Then test that an internal exception in the error app returns 500.
// Write your code here
