Performance: Middleware testing strategies
MEDIUM IMPACT
Middleware testing strategies impact the speed and reliability of request handling in Express apps, affecting response time and user experience.
const middleware = (req, res, next) => {
// Middleware logic
next();
};
// Test middleware function directly by mocking req, res, next
const { jest } = require('@jest/globals');
describe('Middleware unit test', () => {
it('calls next()', () => {
const req = {};
const res = {};
const next = jest.fn();
middleware(req, res, next);
expect(next).toHaveBeenCalled();
});
});const app = require('express')(); app.use((req, res, next) => { // Middleware logic next(); }); // Test calls the middleware by making full HTTP requests using supertest without isolating middleware const request = require('supertest'); describe('Middleware test', () => { it('should call next()', async () => { await request(app).get('/').expect(200); }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Full HTTP request middleware test | N/A | N/A | N/A | [X] Bad |
| Isolated middleware unit test with mocks | N/A | N/A | N/A | [OK] Good |