Middleware helps handle requests in Express apps. Testing it ensures your app works right and handles errors well.
Middleware testing strategies in Express
function middleware(req, res, next) {
// your code here
next();
}Middleware functions take three arguments: req, res, and next.
Call next() to pass control to the next middleware or route handler.
function logger(req, res, next) {
console.log(`${req.method} ${req.url}`);
next();
}function errorHandler(err, req, res, next) {
res.status(500).send('Server error');
}This example shows two middlewares: one adds a property to the request, the other checks it and sends a response. The test uses supertest to simulate a request and prints the response text.
import express from 'express'; import request from 'supertest'; const app = express(); // Middleware to add a property function addProperty(req, res, next) { req.custom = 'test'; next(); } // Middleware to check property function checkProperty(req, res, next) { if (req.custom === 'test') { res.send('Property found'); } else { res.status(400).send('Property missing'); } } app.use(addProperty); app.get('/', checkProperty); // Test using supertest async function runTest() { const response = await request(app).get('/'); console.log(response.text); } runTest();
Use tools like supertest to simulate HTTP requests for testing middleware.
Always test that next() is called to avoid hanging requests.
Test error middleware separately by simulating errors.
Middleware testing ensures your Express app handles requests correctly.
Use simulated requests to check middleware behavior and responses.
Remember to test normal and error cases for full coverage.
Practice
Solution
Step 1: Understand middleware role
Middleware functions handle requests and responses in Express apps.Step 2: Identify testing focus
Testing middleware ensures it processes requests and responses correctly.Final Answer:
To verify that middleware correctly processes requests and responses -> Option AQuick Check:
Middleware testing = request/response handling [OK]
- Confusing middleware testing with UI testing
- Testing unrelated server hardware
- Ignoring request and response handling
Solution
Step 1: Recognize common testing syntax
Using 'request(app).get(path).expect(status, done)' is standard with supertest library.Step 2: Compare options
Only request(app).get('/path').expect(200, done) matches valid syntax for simulating requests in Express tests.Final Answer:
request(app).get('/path').expect(200, done) -> Option AQuick Check:
Simulate request = request(app).get() [OK]
- Using non-existent methods like app.request()
- Confusing middleware with app methods
- Incorrect chaining of test methods
app.use((req, res, next) => {
if (req.query.fail) return next(new Error('Fail'));
res.status(200).send('Success');
});
request(app).get('/?fail=true').expect(500, done);Solution
Step 1: Analyze middleware behavior on fail query
If req.query.fail is true, middleware calls next() with an error, triggering Express error handling.Step 2: Understand test expectation
The test expects status 500, which matches Express default error response status.Final Answer:
The test passes because error triggers 500 status -> Option DQuick Check:
Error passed to next() = 500 response [OK]
- Assuming next() without error sends 200
- Ignoring error passed to next()
- Confusing status codes for errors
app.use((req, res, next) => {
if (!req.headers.auth) return res.status(401);
next();
});
request(app).get('/').expect(401, done);Solution
Step 1: Check middleware response on missing auth
res.status(401) sets status but does not end response without res.send() or res.end().Step 2: Understand test timeout cause
Without ending response, test waits indefinitely causing timeout.Final Answer:
Missing res.send() causes response never to finish -> Option BQuick Check:
res.status() alone doesn't end response [OK]
- Assuming res.status() ends response
- Calling next() after sending response
- Using wrong HTTP method in test
Solution
Step 1: Understand middleware modifies request and calls next()
Testing must confirm request changes and that next() is called to continue flow.Step 2: Choose testing approach
Using a mock request and spying on next() lets you verify both modification and flow control.Final Answer:
Use a mock request object and spy on next() to confirm it was called -> Option CQuick Check:
Mock request + spy next() = full middleware test [OK]
- Ignoring next() call verification
- Testing only response status
- Not providing request data in tests
Ready to prove it?
Pass the test and this pattern moves unknown
