Inspired by the createServer() helper function in the Got tests.
A simple interface for creating a preconfigured Express instance listening for both HTTP and HTTPS traffic.
Ports are chosen at random for HTTP/HTTPS. A self signed certificate is automatically generated, along with an associated CA certificate for you to validate against.
Created because mocking is dirty and can break between Node.js releases. Why mock HTTP requests when you can test locally against a real server in a few lines code?
Install
npm install --save-dev create-test-server
Usage
const createTestServer = require('create-test-server');const server = await createTestServer();console.log(server.url);// http://localhost:5486console.log(server.sslUrl);// https://localhost:5487// This is just an Express route// You could use any Express middleware tooserver.get('/foo', (req, res) => { res.send('bar');});// You can return a body directly tooserver.get('/foo', () => 'bar');server.get('/foo', 'bar');
The following Content-Type headers will be parsed and exposed via req.body:
JSON (application/json)
Text (text/plain)
URL-encoded form (application/x-www-form-urlencoded)
Buffer (application/octet-stream)
You can change body parsing behaviour with the bodyParser option.
createTestServer() has a Promise based API that pairs well with a modern asynchronous test runner such as AVA.
You can create a separate server per test:
import test from 'ava';import got from 'got';import createTestServer from 'create-test-server';test(async t => { const server = await createTestServer(); server.get('/foo', 'bar'); const response = await got(`${server.url}/foo`); t.is(response.body, 'bar'); await server.close();});
Or share a server across multiple tests:
let server;test.before(async () => { server = await createTestServer(); server.get('/foo', 'bar');});test(async t => { const response = await got(`${server.url}/foo`); t.is(response.body, 'bar');});test(async t => { const response = await got(`${
You can also make properly authenticated SSL requests by setting a common name for the server certificate and validating against the provided CA certificate:
Returns a Promise that resolves when both the HTTP and HTTPS servers are listening.
Once the servers are listening, server.url and server.sslUrl will be updated.
Please note, this function doesn't take a port argument, it uses a new randomised port each time. Also, you don't need to manually call this after creating a server, it will start listening automatically.
server.close()
Type: function
Returns a Promise that resolves when both the HTTP and HTTPS servers have stopped listening.
Once the servers have stopped listening, server.url and server.sslUrl will be set to undefined.
Related
create-cert - Super simple self signed certificates