Node.js Fetch Test Server

1.2.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up an Express server and testing its API endpoints using `fetch-test-server` with `async/await` syntax, showing GET and POST requests with JSON bodies and custom headers. It also includes server lifecycle management.

/* 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

view raw JSON →