| Level Navigation: 1 | 2 | 3 | (4ℹ️) | (5ℹ️) | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14⚡ | 15⚡ | (16ℹ️) | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26⚡ | 27⚡ | 28⚡ | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39⚡ | 40⚡ |
Set up Vitest and Supertest to test your Express routes. Start with a simple test for your root route that serves HTML.
Setup:
npm install -D vitest supertest @vitest/coverage-v8tests directory in the root of your project.src/app.js (if you haven’t done the refactor yet, go back to Level 31 first)
// tests/routes/app.test.js
import { describe, it, expect } from 'vitest';
import request from 'supertest';
import app from '../../src/app.js';
describe('Server Routes', () => {
it('serves HTML from root route', async () => {
const res = await request(app).get('/');
expect(res.status).toBe(200);
expect(res.text).toContain('<h1>Hello Express!</h1>');
expect(res.headers['content-type']).toMatch(/html/);
});
});
Notes:
listen() needed: Supertest can work directly with your Express app—you don’t need to call app.listen(). Supertest handles the server setup internally when you pass the app directly to request().await is required: Supertest returns a Promise, so you need await when using async/await syntax to get the response object. Without await, res would be a Promise instead of the response, and your assertions wouldn’t work.