Facebook Pixel

How do I test an Express API?

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.

Verify This Answer

Cross-check this information using these trusted sources:

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?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.