Light my Request

6.6.0 · active · verified Tue Apr 21

light-my-request is a utility library designed to simulate HTTP requests against Node.js HTTP servers without requiring the server to be bound to a network port or even in a listening state. This makes it an ideal tool for writing fast, isolated tests for server logic, as well as for debugging server-side applications. The current stable version is 6.6.0. The project maintains a consistent release cadence, frequently delivering minor versions and patch updates to address features, bug fixes, and performance improvements, as evidenced by the regular 6.x releases. A core differentiator of this library is its ability to interact directly with an `http.createServer` dispatch function, effectively injecting fake request and response objects without relying on actual socket connections. It provides flexibility by supporting both traditional callback-based request handling and modern Promise-based (async/await) patterns, alongside a fluent, chainable API for constructing complex requests.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic GET and POST request injection using the async/await and chained API, showing how to interact with a standard Node.js HTTP dispatch function.

import { inject } from 'light-my-request';
import http from 'node:http';

const dispatch = function (req, res) {
  let body = '';
  req.on('data', chunk => { body += chunk; });
  req.on('end', () => {
    if (req.method === 'POST' && req.url === '/echo') {
      res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': body.length });
      res.end(body);
    } else if (req.url === '/') {
      const reply = 'Hello World';
      res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length });
      res.end(reply);
    } else {
      res.writeHead(404); 
      res.end('Not Found');
    }
  });
};

async function runInjection() {
  try {
    const getResponse = await inject(dispatch).get('/').end();
    console.log('GET /:', getResponse.payload); // Expected: Hello World

    const postResponse = await inject(dispatch)
      .post('/echo')
      .payload('This is a test POST body')
      .end();
    console.log('POST /echo:', postResponse.payload); // Expected: This is a test POST body

  } catch (err) {
    console.error('Injection failed:', err);
  }
}

runInjection();

view raw JSON →