How to Use Jest with Express: Simple Testing Guide
To use
jest with express, write tests that send HTTP requests to your Express app using supertest and assert responses with Jest's functions. Import your Express app into your test files, then use supertest to simulate requests and check results.Syntax
Testing Express apps with Jest usually involves these parts:
- Import Express app: Bring your Express app into the test file.
- Use supertest: A library to simulate HTTP requests to your app.
- Write Jest tests: Use
testoritblocks to define test cases. - Assertions: Use Jest's
expectto check response status, body, headers, etc.
javascript
import request from 'supertest'; import app from './app'; test('GET /endpoint returns 200', async () => { const response = await request(app).get('/endpoint'); expect(response.status).toBe(200); expect(response.body).toEqual({ key: 'value' }); });
Example
This example shows a simple Express app with one route and a Jest test that checks if the route returns the expected JSON and status code.
javascript
// app.js import express from 'express'; const app = express(); app.get('/hello', (req, res) => { res.json({ message: 'Hello, world!' }); }); export default app; // app.test.js import request from 'supertest'; import app from './app'; test('GET /hello returns greeting message', async () => { const response = await request(app).get('/hello'); expect(response.status).toBe(200); expect(response.body).toEqual({ message: 'Hello, world!' }); });
Output
PASS ./app.test.js
✓ GET /hello returns greeting message (XX ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: XX s
Common Pitfalls
Some common mistakes when using Jest with Express include:
- Not exporting the Express app separately from the server listener, which makes testing harder.
- Starting the server inside tests instead of importing the app, causing port conflicts.
- Forgetting to use
awaitwithsupertestrequests, leading to false positives. - Not cleaning up or closing server connections if you start the server in tests.
Correct approach is to export the app without calling app.listen() and use supertest to test routes directly.
javascript
/* Wrong way: starting server inside test file */ import request from 'supertest'; import app from './app'; beforeAll(() => { app.listen(3000); // This can cause conflicts }); test('GET /hello', async () => { const response = await request('http://localhost:3000').get('/hello'); expect(response.status).toBe(200); }); /* Right way: export app and test with supertest */ import request from 'supertest'; import app from './app'; test('GET /hello', async () => { const response = await request(app).get('/hello'); expect(response.status).toBe(200); });
Quick Reference
Tips for smooth Jest testing with Express:
- Always export your Express app without calling
listen(). - Use
supertestto simulate HTTP requests. - Use async/await with
supertestcalls. - Check status codes and response bodies with Jest
expect. - Run tests with
jestcommand after installing dependencies.
Key Takeaways
Export your Express app separately from the server listener for easy testing.
Use supertest with Jest to simulate HTTP requests and check responses.
Always use async/await with supertest to handle asynchronous calls correctly.
Avoid starting the server inside tests to prevent port conflicts.
Check both status codes and response bodies to ensure your routes work as expected.