http-test-server

raw JSON →
3.0.0 verified Sat May 09 auth: no javascript maintenance

A simple, promise-based HTTP server for integration testing in Node.js. v3.0.0 provides an async factory function that starts a server on a random port and returns an object with `baseUrl` and `shutdown()` method. It supports automatic shutdown and collects request body as Buffer. Unlike alternatives like `nock` or `supertest`, this uses a real HTTP server, making it suitable for end-to-end API testing. Released with TypeScript definitions. Maintenance mode since 2022.

error TypeError: httpTestServer is not a function
cause Incorrect import; using named import instead of default.
fix
Use import httpTestServer from 'http-test-server' (default import).
error Cannot read properties of undefined (reading 'baseUrl')
cause Not awaiting the httpTestServer call; server object is a promise.
fix
Add await before httpTestServer: const server = await httpTestServer(...).
error Error: read ECONNRESET
cause Making requests before server is fully started (race condition).
fix
Ensure the server promise resolves before using server.baseUrl.
breaking The server is started asynchronously; you must await the function call. Not doing so leads to undefined behavior.
fix Use `await httpTestServer(handler)` to obtain the server object.
gotcha The request body is collected as a Buffer via stream-to-promise. It is only available after the handler is called; do not access `req.body` before reading the stream yourself.
fix Access `req.body` inside the request handler; it will be a Buffer if the client sends a body.
deprecated The `baseUrl` property includes protocol and port but no trailing slash. Concatenating paths directly may lead to double slashes if path starts with '/'.
fix Use URL constructor: `new URL('/foo', server.baseUrl).href` to avoid double slashes.
gotcha The server listens on a random port (port 0). That port must be free on the system, but conflicts are unlikely.
fix No action needed; the OS assignes a free port automatically.
npm install http-test-server
yarn add http-test-server
pnpm add http-test-server

Creates a server that echoes the request URL, sends a GET request, and shuts down.

import httpTestServer from 'http-test-server';
import got from 'got';

const server = await httpTestServer((req, res) => {
  res.end(req.url);
});

const { body } = await got(`${server.baseUrl}/hello`);
console.log(body); // '/hello'

await server.shutdown();