How to Start the API and Wait for It Before Testing in CI
Tests that start before the server is listening flake, so block on a readiness URL before running them.
Launch the API in the background with &, then run npx wait-on <url> (or a curl retry loop) so the suite starts only once the server answers.
Steps
- Start the server in the background so the step does not block.
- Run
npx wait-on http://localhost:PORT/healthto gate on readiness. - Only then run the test command.
Workflow
.github/workflows/ci.yml
steps:
- run: npm start &
- run: npx wait-on --timeout 60000 http://localhost:3000/health
- run: npm run test:apiPure-shell alternative
Terminal
for i in $(seq 1 30); do
curl -sf http://localhost:3000/health && break
echo "waiting for api ($i)"; sleep 2
done
curl -sf http://localhost:3000/health || { echo "api never came up"; exit 1; }Gotchas
- Always set a timeout so a server that never boots fails the job instead of hanging.
- Poll a real readiness endpoint, not the TCP port, so you wait for the app and not just the socket.
Related guides
How to Give API Tests a Real Database With Service Containers in CIBack API tests with a real Postgres in GitHub Actions using a service container with health checks, so integr…
How to Run REST API Tests With pytest and requests in CIRun integration tests against a REST API in GitHub Actions using pytest and the requests library, with a JUni…
How to Write Rate-Limit-Aware API Tests in CIKeep API tests from tripping rate limits in GitHub Actions by honoring Retry-After, backing off on 429s, and…