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.
npm install create-test-serverVerified import paths — ran on the pinned version, not inferred.
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.
Refactor code to use the exposed methods and properties of the `server` object returned by `createTestServer()`. Avoid accessing `server.app`, `server.http`, or `server.https` directly if these were previously used.
For authenticated SSL, pass `ca: server.caCert` to your HTTP client and set the `Host` header to match the `certificate` option provided during server creation (e.g., `createTestServer({ certificate: 'foobar.com' })`). Alternatively, for unauthenticated but encrypted connections, set `rejectUnauthorized: false` on your client (e.g., `got(url, { rejectUnauthorized: false })`).Always use `server.url` and `server.sslUrl` properties to get the dynamically assigned ports for each test run. Do not hardcode port numbers.
Always `await createTestServer()` before interacting with the returned `server` object, especially in asynchronous test functions: `const server = await createTestServer();`.
Ensure `createTestServer()` is `await`ed. Example: `const server = await createTestServer(); server.get('/foo', 'bar');`When making HTTPS requests, either provide the `server.caCert` to your client and set the `Host` header to match the server's certificate common name, or disable SSL certificate validation in the client (e.g., `rejectUnauthorized: false` for `got`).
If in ESM, use `import createTestServer from 'create-test-server';`. If in CommonJS, use `const createTestServer = require('create-test-server');`. Ensure your project's module system configuration aligns with your import statements.