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.
Previous
What is Passport.js and how does it integrate with Express?
Next
What is Express.js Router-level middleware?
More Express.js Questions
View all →- Intermediate How do you implement JWT authentication in Express.js?
- Intermediate What is Express middleware chaining and how does it work?
- Intermediate What is the helmet package and why should you use it?
- Intermediate How do you implement rate limiting in Express.js?
- Intermediate What is input validation and how do you do it in Express?