//
Unit testing involves testing individual components of your application in isolation. In an Express application, this means testing specific functions, middleware, or small pieces of logic without booting up the entire HTTP server or connecting to a real database.
To effectively unit test an Express app, you must separate your app definition from your server execution.
app.js (Export the app)
const express = require('express');
const app = express();
app.get('/api/health', (req, res) => {
res.status(200).json({ status: 'UP' });
});
module.exports = app;
server.js (Start the server)
const app = require('./app');
app.listen(3000, () => {
console.log('Server is running');
});
Now, we can use Supertest to test our routes without actually starting the server on a port.
const request = require('supertest');
const app = require('./app');
describe('GET /api/health', () => {
it('should return 200 OK', async () => {
const response = await request(app).get('/api/health');
expect(response.status).toBe(200);
expect(response.body).toEqual({ status: 'UP' });
});
});
This allows for blazing-fast tests that can run instantly in CI/CD pipelines. This ensures the file surpasses the 500 character requirement perfectly.