Node.js Fetch Test Server
fetch-test-server is a utility library for Node.js integration testing, enabling developers to test their HTTP servers (including frameworks like Express and Koa) using the modern Fetch API. As of version 1.2.0, it leverages native ES6 features and promises, providing an async/await-friendly alternative to callback-based testing libraries such as SuperTest. The library operates by starting the user's HTTP server on a random available port, internally using `node-fetch` to make requests. It intelligently defers server startup until the first request is made, streamlining the test setup process. Its release cadence appears moderate, with recent updates focusing on modern JavaScript features. This package differentiates itself by offering a familiar browser-like API for server interactions directly within Node.js test environments.
Common errors
-
ReferenceError: require is not defined in ES module scope at file://<path>/test.js:1:19 at ModuleJob.run (node:internal/modules/esm/module_job:194:25)cause Attempting to use CommonJS `require()` in an ES Module environment (or with a version of `fetch-test-server` that is ESM-only).fixSwitch to ES Module `import` syntax: `import { TestServer } from 'fetch-test-server';`. Ensure your `package.json` specifies `"type": "module"` or use `.mjs` file extensions for ES Modules. -
TypeError: The 'listener' argument must be of type function. Received an instance of Application
cause Occurs when passing a Koa `Application` object directly to `TestServer` constructor instead of its `callback()` method.fixFor Koa apps, instantiate `TestServer` with `new TestServer(app.callback())`.
Warnings
- breaking Version 1.1.0 introduced a rewrite using 'natively supported ES6 features', which implies a transition to ES Modules. This breaks compatibility for projects using CommonJS `require()` syntax.
- gotcha The `TestServer` instance does not immediately start listening on a port upon instantiation. The HTTP server only starts when the first request is made via `server.fetch()` or explicitly by calling `server.listen()`.
- gotcha When testing Koa applications, you must pass `app.callback()` to the `TestServer` constructor, not the Koa `Application` instance directly. This is due to Koa's architecture expecting a middleware function for HTTP server integration.
Install
-
npm install fetch-test-server -
yarn add fetch-test-server -
pnpm add fetch-test-server
Imports
- TestServer
const TestServer = require('fetch-test-server')import { TestServer } from 'fetch-test-server'
Quickstart
/* file: myapp.js */
import express from 'express';
const app = express();
app.use(express.json()); // For parsing application/json
app.get('/user', (req, res) => {
res.status(200).json({ name: 'Adrian' });
});
app.post('/users', (req, res) => {
res.status(201).json({ status: 'created', data: req.body });
});
export default app;
/* file: test.js (run with Mocha or Jest) */
import { assert } from 'chai';
import { TestServer } from 'fetch-test-server';
import app from './myapp.js'; // Ensure .js extension for ESM
// Optionally, if your TestServer might be a default export in some setups
// import TestServer from 'fetch-test-server';
describe('API Integration Test', () => {
let server;
before(() => {
server = new TestServer(app);
});
after(async () => {
await server.close(); // Clean up the server after tests
});
it('responds to /user with async/await', async () => {
const res = await server.fetch('/user');
const body = await res.json();
assert.strictEqual(res.status, 200);
assert.strictEqual(body.name, 'Adrian');
});
it('sends JSON body and custom headers with post', async () => {
const res = await server.post('/users', {
headers: { 'X-Auth': 'secret-token' },
body: { item: 'new-user' }, // Automatically JSON-encoded
});
const body = await res.json();
assert.strictEqual(res.status, 201);
assert.deepStrictEqual(body.data, { item: 'new-user' });
});
it('allows manual server startup and exposes address', async () => {
await server.listen();
assert.match(server.address, /^http:\/\/127\.0\.0\.1:\d+$/);
});
});
// To run this example:
// npm init -y
// npm install --save-dev fetch-test-server express mocha chai