How do I test Express controllers?
Use Jest and supertest. Import the Express app, send requests with supertest, assert on the response. Test happy paths and error paths (validation, not found, conflict). Use a test database so tests do not pollute dev data.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Writing Clean API Controllers in Express
Parse the request, call a service or model, send the response with the right status code, and handle errors with ApiError. Keep it thin. Move complex logic to a services layer. Use asyncHandler so rejections go to the error handler.
Yes for anything non-trivial. Controllers orchestrate; services do the work. Services are reusable and testable. Without them, controllers become long and hard to test.
Use a serializer (a toUserDTO function) that picks only the safe fields. Never return passwordHash, JWT secrets, or internal IDs. Apply the serializer before sending the response.
Still have questions?
Browse all our FAQs or reach out to our support team
