0
0
ExpressHow-ToBeginner · 3 min read

How to Test Middleware in Express: Simple Guide

To test middleware in Express, you can call the middleware function directly with mock req, res, and next objects or use a testing library like Supertest to simulate HTTP requests. This lets you verify middleware behavior such as modifying requests, sending responses, or calling next() properly.
📐

Syntax

An Express middleware function has the signature (req, res, next). It receives the request and response objects, and a next function to pass control to the next middleware.

  • req: The HTTP request object.
  • res: The HTTP response object.
  • next: A function to call the next middleware.

You test middleware by calling it with mock versions of these objects.

javascript
function middleware(req, res, next) {
  // Middleware logic here
  next();
}
💻

Example

This example shows how to test a simple middleware that adds a property to req. We use Jest for assertions and mock req, res, and next.

javascript
const middleware = (req, res, next) => {
  req.customProperty = 'testValue';
  next();
};

// Mock objects
const req = {};
const res = {};
const next = jest.fn();

// Run middleware
middleware(req, res, next);

// Test results
console.log(req.customProperty); // 'testValue'
console.log(next.mock.calls.length); // 1
Output
testValue 1
⚠️

Common Pitfalls

Common mistakes when testing middleware include:

  • Not mocking next properly, so you can't verify if it was called.
  • Forgetting to mock req or res properties your middleware uses.
  • Not handling asynchronous middleware correctly by missing async/await or callbacks.

Always ensure mocks match what your middleware expects.

javascript
/* Wrong: next is not mocked, so you can't check if it was called */
const middleware = (req, res, next) => {
  next();
};

// middleware({}, {}, undefined); // This will throw an error if next is undefined

/* Right: next is a jest.fn() mock to track calls */
const next = jest.fn();
middleware({}, {}, next);
console.log(next.mock.calls.length); // 1
Output
1
📊

Quick Reference

Tips for testing Express middleware:

  • Mock req, res, and next objects based on middleware needs.
  • Use jest.fn() or similar to spy on next calls.
  • For middleware that sends responses, mock res.send or res.status to verify output.
  • Use Supertest to test middleware in the context of full HTTP requests.
  • Handle async middleware with async/await or done callbacks.

Key Takeaways

Test middleware by calling it with mock req, res, and next objects.
Always mock next as a function to verify it is called.
Use Supertest for integration-style tests with HTTP requests.
Mock only the parts of req and res your middleware uses.
Handle async middleware with async/await or callbacks.