reqres

raw JSON →
3.0.1 verified Sat Apr 25 auth: no javascript

Stub request and response objects for testing Express applications and middleware. Provides `req()` and `res()` functions that create mock objects with sensible defaults and sinon stubs on methods. Version 3.0.1 is current, maintained as needed. Key differentiator: integrates sinon for stub/spy assertions, customisable sinon instance, emits 'end' events on response methods. Alternative to node-mocks-http or express-mocks-http.

error TypeError: reqres.req is not a function
cause Importing named exports incorrectly in CommonJS when using default import pattern.
fix
Use const { req } = require('reqres');
error Cannot find module 'sinon'
cause Sinon is a peer dependency; not installed automatically.
fix
Run npm install sinon --save-dev
error AssertionError: expected res.json to have been called with arguments { user: '...' } but it was never called
cause Response method 'end' event may not be emitted if async middleware doesn't call next() or res.json() before assertion.
fix
Wrap assertion in res.on('end', ...) callback.
breaking Default headers are not set on response object. res.setHeader and res.getHeader may be stubs that do not store values.
fix Provide custom headers via res({ headers: {...} }) or manually set in tests.
deprecated Using reqres.req() and reqres.res() as non-destructured calls is deprecated in favor of destructured imports.
fix Use const { req, res } = require('reqres'); then call req(), res().
gotcha The 'end' event on res is emitted only for methods like json, send, sendStatus, etc. Not all response methods emit it.
fix Check source or readme for full list of methods that emit 'end'.
gotcha reqres does not support ES modules (import). Must use require().
fix Use CommonJS require() or find an ESM-compatible alternative.
npm install reqres
yarn add reqres
pnpm add reqres

Shows creating mock req and res objects with custom properties and invoking middleware.

const { req, res } = require('reqres');
const myMiddleware = (req, res, next) => {
  req.session = req.session || {};
  req.session.path = req.path;
  next();
};

const mockReq = req({ path: '/test', session: {} });
const mockRes = res();

myMiddleware(mockReq, mockRes, (err) => {
  console.log(mockReq.session.path); // '/test'
});