Intermediate LevelExpress JS
How do you write automated API integration tests for Express endpoints using Supertest?
❓ Interview Prompt: Explain API integration testing with Supertest, passing express app without listening on ports, asserting status codes, and payload checks.
Supertest is the standard library for HTTP integration testing in Node.js, pairing with Vitest or Jest.
Key Feature:
Supertest accepts the un-listened Express 'app' instance directly ('request(app)'). It spins up an ephemeral HTTP server behind the scenes, executes HTTP calls, and asserts status codes without requiring manual port management!
Code Implementation Example
javascript
import request from 'supertest';
import { test, expect } from 'vitest';
import app from './app.js'; // Import un-listened Express app
test('GET /api/users returns 200 and JSON array', async () => {
const response = await request(app)
.get('/api/users')
.set('Authorization', 'Bearer valid-token')
.expect('Content-Type', /json/)
.expect(200);
expect(Array.isArray(response.body)).toBe(true);
});💡Automated Express API endpoint integration test using Supertest and Vitest.
🎯 Interview Key Takeaway
Pass the un-listened Express app instance to Supertest (request(app)) to execute fast API integration tests.
#Supertest#Integration Testing#Vitest#Intermediate
Back to all Express JS Questions→