Create Test Server

3.0.1 · active · verified Sun Apr 19

create-test-server is a utility that creates a minimal Express.js server for robust HTTP and HTTPS testing, operating on randomly chosen ports. It automatically generates self-signed SSL certificates with an associated CA certificate, enabling authenticated SSL requests in test environments. Currently at version 3.0.1, its release cadence follows semantic versioning, with major versions indicating breaking changes. A key differentiator is its approach to testing: instead of fragile HTTP mocking that can break across Node.js versions (e.g., Nock), it advocates for testing against a real, locally running server. It handles JSON, plain text, URL-encoded forms, and buffer bodies by default, making it versatile for various API testing scenarios. The library provides a Promise-based API that integrates seamlessly with modern asynchronous test runners like AVA.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating a test server, defining a simple GET route that returns text, and a POST route that processes a JSON body. It then uses the `got` library to make requests and `ava` for assertions, showcasing both HTTP and Express-like request handling, followed by proper server cleanup.

import test from 'ava';
import got from 'got';
import createTestServer from 'create-test-server';

test('should respond to a basic GET request with text', async t => {
  const server = await createTestServer();
  server.get('/hello', 'world');

  const response = await got(`${server.url}/hello`);
  t.is(response.body, 'world');

  await server.close();
});

test('should handle POST requests with JSON body', async t => {
  const server = await createTestServer();
  server.post('/data', (req, res) => {
    res.json({ received: req.body });
  });

  const testData = { message: 'hello from client' };
  const response = await got.post(`${server.url}/data`, {
    json: testData,
    responseType: 'json'
  });

  t.deepEqual(response.body, { received: testData });
  await server.close();
});

view raw JSON →