How do I test authenticated routes with supertest?
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.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Writing API Tests in Node.js With Jest and supertest
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.
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.
Still have questions?
Browse all our FAQs or reach out to our support team
