serve-once

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

A utility for testing Express middleware by serving exactly one HTTP request then closing the server. It creates an HTTP server on a free port, runs the middleware, serves one request, and resolves with the response body. The current stable version is 3.0.2, released in early 2024. It supports GET, POST, PUT, DELETE, HEAD, and other methods. The package was rewritten in v3 to remove node-fetch dependency and requires Node >=18. It returns responses as string, JSON, buffer, or stream. It is lightweight and similar to supertest but simpler and focused on single-request testing.

error TypeError: request.get is not a function
cause Calling request.get before initializing the factory or using wrong import.
fix
Ensure you call require('serve-once')(middleware) which returns an object with request method. Use const {request} = serveOnce(middleware); then request.get('/path')
error ERR_MODULE_NOT_FOUND: Cannot find module 'serve-once'
cause Importing serve-once as a named export in ESM.
fix
Use CommonJS require via createRequire or use dynamic import: const serveOnce = (await import('serve-once')).default;
breaking v3 drops support for Node < 18. Requires Node >= 18.
fix Upgrade Node to version 18 or later.
deprecated v3 removed node-fetch dependency; internal HTTP client uses native fetch (available in Node 18+).
fix Ensure your environment supports global fetch (Node 18+).
gotcha The default export is not a class but a factory function. CommonJS require is typical as there is no named import.
fix Use const serveOnce = require('serve-once'); const {request} = serveOnce(middleware);
gotcha The request function returns a response body as a string by default. To get JSON, set type option to 'json'.
fix const result = await request('get', '/', { type: 'json' });
npm install serve-once
yarn add serve-once
pnpm add serve-once

Demonstrates basic usage: create server with middleware, make GET request, get response as string. Also shows request.get() with custom options.

import { createRequire } from 'module';
const require = createRequire(import.meta.url);

const pullout = require('pullout');
const serveOnce = require('serve-once');

const middleware = (options = 'hello') => (req, res) => {
  res.end(JSON.stringify(options));
};

const { request } = serveOnce(middleware);

const response = await request('get', '/');
console.log(response); // 'hello'

const result2 = await request.get('/', {
  options: 'world'
});
console.log(result2); // 'world'