How to Implement API Integration Tests
Test an API end to end: start the app with real routes, call it over HTTP, assert status and body, and isolate the data per test.
On this page
Introduction
A unit test of a handler calls the function with a constructed input and asserts the returned value. It is fast and focused, and it skips everything between the incoming bytes and the handler: the routing, the middleware, the body parsing, the serialization, and the status mapping. Those layers are where an API breaks in ways the unit test cannot see, so an integration test sends a real request through all of them and asserts the real response.
This tutorial implements an API integration test: start the app with its real routes, call it over HTTP, isolate the data per test, and stub only the true externals. The examples use an HTTP client against the app, and the approach applies to any HTTP API.
Start the app with real routes and middleware
The test starts the application the same way the process does, so it exercises the real routing table, the real middleware chain, and the real serialization. A handler tested in isolation proves the handler’s logic, not that the route is wired or that the middleware runs. The integration test proves the request path end to end, which is what a caller experiences.
Start it once per suite, not per test, and share the running app, because starting the server is the expensive part. Bind to an ephemeral port so parallel runs do not collide, and read the port from the server so the client uses the real one. The suite’s setup starts the app, and the teardown stops it.
import { createApp } from './app';
import { beforeAll, afterAll } from 'vitest';
let server, baseUrl;
beforeAll(async () => {
const app = await createApp({ db: await startTestDb() }); // real db, real routes
server = app.listen(0); // ephemeral port
baseUrl = 'http://127.0.0.1:' + server.address().port;
});
afterAll(async () => { server.close(); });
Call the API over HTTP and assert the response
Send a real HTTP request and assert the status, the body, and the headers, as a client would. This covers the serialization, the status mapping, and the content type, which a handler unit test skips. Assert on the fields the client relies on, and assert the status, because a body with the right field and the wrong status is still a broken API.
Treat the test like a client: build the request with the real headers and body, and parse the response as the client would. This catches the content-type mismatch, the missing CORS header, and the body that serializes with the wrong field name, none of which a direct handler call would reveal.
it('creates an order and returns 201 with the id', async () => {
const res = await fetch(baseUrl + '/orders', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ customerId: 1, items: [{ sku: 'a', qty: 2 }] }),
});
expect(res.status).toBe(201); // the status mapping
const body = await res.json();
expect(body.id).toBeTypeOf('number'); // the serialized body
});
it('returns 422 for an invalid body', async () => {
const res = await fetch(baseUrl + '/orders', {
method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"items":[]}',
});
expect(res.status).toBe(422); // the validation mapping
});
Isolate the data per test
Integration tests share a database, so a test that writes affects the next. Isolate per test with a transaction rolled back at the end, or with a fresh schema, so each test starts clean. Isolation also means the tests can run in parallel without interfering, and the failures are independent: one test’s failure does not cascade into the others.
For requests that must commit, a transaction rollback does not work, so use a truncate-before-test or a schema-per-test. Whatever the method, the invariant is that a test never sees another test’s rows, so its assertions are about its own data. This is the same isolation as a database unit test, applied at the API level.
import { beforeEach } from 'vitest';
let tx;
beforeEach(async () => {
tx = await db.begin(); // request-scoped: the app uses tx for this test
await seed(tx, { customers: [{ id: 1 }] }); // known, test-local data
});
afterEach(async () => { await tx.rollback(); }); // no rows survive the test
Stub only the externals you cannot run
An integration test should let the application’s own layers run and replace only the services the test cannot run, such as a third-party API or a payment provider. Stubbing the database or an internal service turns the test back into a unit test with more setup. Replace the outermost dependencies, and keep the layers between the request and them real.
Stub the external with a controllable fake that returns a known response, so the test is deterministic and does not depend on a remote service being up or on its data. A test that calls a real third-party API is slow, flaky, and rate-limited, which is why the external is the one thing to replace, and only it.
Test the errors and the end-to-end flow
Beyond the happy path, test the error responses end to end: an invalid body yields the validation status, a missing resource yields 404, an unauthorized request yields 401, and a dependency failure yields the degraded status. Each asserts the status the client branches on and the error body it parses, which is the API’s contract at the boundary.
Test a multi-step flow, such as create then read then delete, to confirm the pieces work together. A flow test catches a state that one endpoint sets wrong for the next, which single-endpoint tests miss. Keep a few flow tests for the critical paths and many single-endpoint tests for the details.
# end-to-end flow: create, read, delete, then confirm it is gone
curl -s -X POST -H 'content-type: application/json' -d '{"customerId":1,"items":[{"sku":"a","qty":1}]}' $BASE/orders
curl -s $BASE/orders/1
curl -s -X DELETE $BASE/orders/1
curl -s -o /dev/null -w '%{http_code}\n' $BASE/orders/1 # 404
Common pitfalls
Testing the handler in isolation so the routing and serialization are never covered, sharing a database without isolation so tests are order-dependent, stubbing internal services so the test is not an integration, calling a real external API so the test is slow and flaky, and asserting the body without the status are the recurring mistakes. A started app, real HTTP calls, per-test isolation, external-only stubs, and status assertions address them.
Conclusion
An API integration test sends a real request through the app’s real layers. Start the app with its routes and middleware, call it over HTTP and assert the status and body, isolate the data per test, and stub only the externals. Self-check by asserting an invalid body yields the validation status and a create-then-read flow works end to end. Then the request path a caller experiences is tested, not just the handler.
Sources: MDN: HTTP request and response, Supertest: HTTP assertions, Go: httptest package.
FAQ
- How is this different from a unit test of the handler?
- A handler unit test calls the function with a constructed input, so it skips the routing, middleware, serialization, and status mapping. An integration test sends a real request through those, which is where mismatches live, such as a body that serializes wrong or a status that is never set.
- Should integration tests use a real database?
- Prefer a real database in a container, so the SQL and constraints are exercised. Stub only the externals you cannot run, such as a third-party API. The closer the test is to production, the more it catches.
Report a problem with this articleOpens a pre-filled issue on GitHub.