{"id":17925,"library":"reqresnext","title":"Express Middleware Testing Helper","description":"reqresnext is a minimalist utility designed for testing Express.js middleware. It provides mock implementations of the `req`, `res`, and `next` objects, allowing developers to isolate and test middleware functions without a full Express server setup. The current stable version is 1.7.0, released in February 2022. Releases are infrequent, primarily focusing on bug fixes and minor enhancements rather than new features. Its key differentiator is its small footprint and focused scope, aiming to provide just enough mocking capability for unit testing, contrasting with more comprehensive HTTP mocking libraries that might offer broader server-side simulation. It ships with robust TypeScript type definitions, making it well-suited for modern JavaScript and TypeScript projects that prioritize type safety in their testing environments.","status":"maintenance","version":"1.7.0","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/antongolub/reqresnext","tags":["javascript","mock","express mock","http mock","mock testing","req res next","typescript"],"install":[{"cmd":"npm install reqresnext","lang":"bash","label":"npm"},{"cmd":"yarn add reqresnext","lang":"bash","label":"yarn"},{"cmd":"pnpm add reqresnext","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"Use named import for the request mock factory. CommonJS `require` syntax is also supported but not recommended for modern projects.","wrong":"const { mockReq } = require('reqresnext')","symbol":"mockReq","correct":"import { mockReq } from 'reqresnext'"},{"note":"Use named import for the response mock factory. Ensure correct destructuring if using CommonJS require.","wrong":"const res = require('reqresnext').mockRes()","symbol":"mockRes","correct":"import { mockRes } from 'reqresnext'"},{"note":"The `mockNext` function is a named export, not a default export. No arguments are typically needed for `mockNext()`.","wrong":"import mockNext from 'reqresnext'","symbol":"mockNext","correct":"import { mockNext } from 'reqresnext'"},{"note":"Import TypeScript types separately for type hinting and interface extension, allowing for type-safe manipulation of mock objects.","symbol":"MockRequest","correct":"import type { MockRequest } from 'reqresnext'"}],"quickstart":{"code":"import { mockReq, mockRes, mockNext } from 'reqresnext';\nimport { Request, Response, NextFunction } from 'express';\n\n// Example Express middleware\nconst authMiddleware = (req: Request, res: Response, next: NextFunction) => {\n  if (req.headers && req.headers.authorization === 'Bearer my-secret-token') {\n    // In a real app, you might decode a JWT and set req.user\n    (req as any).user = { id: 1, name: 'Test User' }; \n    next();\n  } else {\n    res.status(401).send('Unauthorized');\n  }\n};\n\n// Basic test using a common testing framework like Jest\ndescribe('authMiddleware', () => {\n  it('should allow access with a valid token', () => {\n    const req = mockReq({ headers: { authorization: 'Bearer my-secret-token' } });\n    const res = mockRes();\n    const next = mockNext();\n\n    authMiddleware(req as unknown as Request, res as unknown as Response, next);\n\n    expect(next).toHaveBeenCalledTimes(1);\n    expect((req as any).user).toEqual({ id: 1, name: 'Test User' });\n    expect(res.statusCode).toBe(200); // Default status if next() is called\n    expect(res.send).not.toHaveBeenCalled();\n  });\n\n  it('should deny access without a token', () => {\n    const req = mockReq(); // No authorization header\n    const res = mockRes();\n    const next = mockNext();\n\n    authMiddleware(req as unknown as Request, res as unknown as Response, next);\n\n    expect(next).not.toHaveBeenCalled();\n    expect(res.statusCode).toBe(401);\n    expect(res.send).toHaveBeenCalledWith('Unauthorized');\n  });\n});","lang":"typescript","description":"Demonstrates how to mock `req`, `res`, and `next` objects and unit test an Express middleware function using Jest expectations."},"warnings":[{"fix":"Upgrade to `v1.7.0` or later. Ensure your middleware accesses headers using lowercase keys (e.g., `req.headers['content-type']`).","message":"Prior to `v1.7.0`, incoming request headers might not have been consistently lowercased, which is standard behavior for HTTP headers. Middleware relying on specific header casing might have behaved unexpectedly.","severity":"gotcha","affected_versions":"<1.7.0"},{"fix":"Upgrade to `v1.6.5` or later to ensure `res.end()` behavior correctly accumulates the response body.","message":"In versions prior to `v1.6.5`, the `res.end()` mock might not have correctly concatenated the response body across multiple calls, potentially leading to incomplete or incorrect response content in tests.","severity":"gotcha","affected_versions":"<1.6.5"},{"fix":"For complex scenarios involving streaming or low-level HTTP features, consider integration tests with a real Express server or a more comprehensive HTTP mocking library if `reqresnext` proves insufficient.","message":"While `reqresnext` provides robust mocks for Express middleware testing, the mock objects are not full replicas of native Node.js `http.IncomingMessage` and `http.ServerResponse` objects. Certain advanced features, event emitters, or stream manipulations might not be fully supported.","severity":"gotcha","affected_versions":"*"},{"fix":"Use type assertions like `req as unknown as Request` or `res as unknown as Response` when calling middleware with `reqresnext` mock objects, especially if your middleware is strictly typed.","message":"TypeScript users should be aware that casting `MockRequest` and `MockResponse` to `express.Request` and `express.Response` might be necessary when passing them to middleware functions, as the types are not directly compatible without explicit assertion due to potential interface differences.","severity":"gotcha","affected_versions":">=1.6.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"When adding custom properties (e.g., from an authentication middleware), either use `(req as any).user = ...` for quick fixes or extend the `MockRequest` interface via TypeScript declaration merging (`declare module 'reqresnext' { interface MockRequest { user?: { id: number; name: string; }; } }`) for better type safety.","cause":"Attempting to assign or access custom properties on the mocked request object without explicit type assertion or declaration merging in TypeScript, leading to type errors.","error":"Property 'user' does not exist on type 'MockRequest'."},{"fix":"Ensure `req.headers` and any specific header properties are provided in the `mockReq` options when creating the mock request: `mockReq({ headers: { authorization: 'Bearer token' } })`.","cause":"Accessing `req.headers.authorization` when `req.headers` was not initialized or the `authorization` property was not provided in the `mockReq` options.","error":"TypeError: Cannot read properties of undefined (reading 'authorization')"},{"fix":"Verify that `mockNext()` is being used, as it returns a Jest-compatible mock function by default. Double-check your middleware's conditional logic to ensure `next()` is indeed invoked when expected, and that no early `return` or `res.send()` prevents its execution.","cause":"The `next` function mock might not be correctly recognized by your testing framework, or the middleware's logic is not calling `next()` under the specific test conditions you've set up.","error":"expect(next).toHaveBeenCalled() fails but middleware appears to call next()"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}