Mock Express Request

0.2.2 · abandoned · verified Wed Apr 22

Mock Express Request is a Node.js library designed to create mock HTTP request objects for unit testing Express.js applications. It is based on the `mock-req` package and aims to provide an instance with properties and methods similar to a real Express HTTP request. The package is currently at version 0.2.2 and appears to be abandoned, with no significant updates or maintenance activity in approximately nine years. Due to its age, it lacks modern features such as native ES Module support and deep integration with contemporary testing frameworks like Jest, making it less suitable for current Node.js and Express.js projects. Developers are generally advised to consider more actively maintained alternatives like `node-mocks-http` or `@jest-mock/express` for robust testing in modern environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to create basic and advanced mock Express HTTP request objects, configuring method, URL, headers, cookies, and body, then accessing these properties.

const MockExpressRequest = require('mock-express-request');

// Basic usage: Create a mock GET request to a specific URL
const basicRequest = new MockExpressRequest({
    method: 'GET',
    url: '/api/users/123?profile=full'
});

console.log(`Method: ${basicRequest.method}`); // Expected: GET
console.log(`URL: ${basicRequest.url}`);       // Expected: /api/users/123?profile=full
console.log(`Path: ${basicRequest.path}`);     // Expected: /api/users/123
console.log(`Query 'profile': ${basicRequest.param('profile')}`); // Expected: full

// More advanced usage: Mock a PUT request with headers and cookies
const advancedRequest = new MockExpressRequest({
    method: 'PUT',
    url: '/data/item/abc',
    cookies: { session_id: 'MY_SESSION_TOKEN', remember_me: 'true' },
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ABCDEFG'
    },
    body: { name: 'New Item', value: 42 }
});

console.log(`Host: ${advancedRequest.hostname}`); // Access Express-like properties (often defaults to 'localhost')
console.log(`Request body: ${JSON.stringify(advancedRequest.body)}`);
console.log(`Cookie 'session_id': ${advancedRequest.cookies.session_id}`);
console.log(`Header 'Content-Type': ${advancedRequest.get('Content-Type')}`); // Using .get() for headers

view raw JSON →