🚀 Express.js Intermediate

How do you test an Express.js API?

Answer

The standard approach uses Jest (test runner) with Supertest (HTTP assertions). Supertest lets you make HTTP requests to your Express app without starting a real server. Example: const request = require('supertest'); const app = require('./app'); it('GET /users returns 200', async () => { const res = await request(app).get('/users'); expect(res.status).toBe(200); expect(res.body).toBeInstanceOf(Array); });. For database interactions, use a test database, mock the DB layer with Jest mocks, or use in-memory databases. Separate the Express app creation (app.js) from the server startup (server.js) so tests can import the app without starting a listening server. Test both happy paths and error cases.