Testing Express APIs

API tests check whether endpoints behave correctly.

They are especially useful for auth, validation, and error cases.

What to test

For an endpoint, test:

Example test thinking

For:

POST /users

Test:

Test app export pattern

It is useful to export the Express app without starting the server.

export const app = express()

Then start separately:

app.listen(3000)

Tests can import app directly.

Interview answer

Express API tests should verify successful responses and failure cases such as validation errors, unauthorized requests, forbidden access, and not found responses. A common pattern is exporting the Express app separately from listen so tests can call routes without starting a real server.