Use Jest and supertest. Import the Express app, send requests with supertest, assert on the response. Test happy paths and error paths (validation, auth, not found, conflict). Use a test database and clean between tests.
Writing API Tests in Node.js With Jest and supertest
How do I test an Express API?
The answer
More FAQs in Writing API Tests in Node.js With Jest and supertest
So tests do not pollute dev or prod data. Set MONGODB_URI to a test database in your test env. Clean it between tests (User.deleteMany({})) so tests are independent and reproducible.
Happy path (valid input works), validation errors (missing or bad fields return 400), auth errors (missing or invalid token returns 401), authorization (wrong role returns 403), not found (404), and conflict (409). Test status codes AND response shapes.
Log in first to get a token. Then set the cookie or Authorization header on subsequent requests: request(app).get('/me').set('Cookie', [`token=${token}`]). Assert the status and body.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.