• Stars
    star
    121
  • Rank 293,924 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Creates a minimal Express server for testing

create-test-server

Creates a minimal Express server for testing

Build Status Coverage Status npm npm

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:5486
console.log(server.sslUrl);
// https://localhost:5487

// This is just an Express route
// You could use any Express middleware too
server.get('/foo', (req, res) => {
  res.send('bar');
});

// You can return a body directly too
server.get('/foo', () => 'bar');
server.get('/foo', 'bar');

// server.url + '/foo' and server.sslUrl + '/foo' will respond with '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(`${server.url}/foo`);
  t.is(response.statusCode, 200);
});

test.after(async () => {
	await server.close();
});

You can also make properly authenticated SSL requests by setting a common name for the server certificate and validating against the provided CA certificate:

test(async t => {
  const server = await createTestServer({ certificate: 'foobar.com' });
  server.get('/foo', 'bar');

  const response = await got(`${server.sslUrl}/foo`, {
    ca: server.caCert,
    headers: { host: 'foobar.com' }
  });
  t.is(response.body, 'bar');

  await server.close();
});

You can still make an SSL connection without messing about with certificates if your client supports unauthorised SSL requests:

test(async t => {
  const server = await createTestServer();
  server.get('/foo', 'bar');

  const response = await got(`${server.sslUrl}/foo`, {
    rejectUnauthorized: false
  });
  t.is(response.body, 'bar');

  await server.close();
});

You can also easily stop/restart the server. Notice how a new port is used when we listen again:

const server = await createTestServer();
console.log(server.port);
// 56711

await server.close();
console.log(server.port);
// undefined

await server.listen();
console.log(server.port);
// 56804

API

createTestServer([options])

Returns a Promise which resolves to an (already listening) server.

options

Type: object

options.certificate

Type: string, object
Default: undefined

SSL certificate options to be passed to createCert().

options.bodyParser

Type: object | boolean
Default: undefined

Body parser options object to be passed to body-parser methods.

If set to false then all body parsing middleware will be disabled.

server

Express instance resolved from createTestServer()

This is just a normal Express instance with a few extra properties.

server.url

Type: string, undefined

The url you can reach the HTTP server on.

e.g: 'http://localhost:5486'

undefined while the server is not listening.

server.port

Type: number, undefined

The port number you can reach the HTTP server on.

e.g: 5486

undefined while the server is not listening.

server.sslUrl

Type: string, undefined

The url you can reach the HTTPS server on.

e.g: 'https://localhost:5487'

undefined while the server is not listening.

server.sslPort

Type: number, undefined

The port number you can reach the HTTPS server on.

e.g: 5487

undefined while the server is not listening.

server.caCert

Type: string

The CA certificate to validate the server certificate against.

server.http

Type: http.server

The underlying HTTP server instance.

server.https

Type: https.server

The underlying HTTPS server instance.

server.listen()

Type: function

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

License

MIT © Luke Childs

More Repositories

1

zsh-nvm

Zsh plugin for installing, updating and loading nvm
Shell
2,077
star
2

dockerpi

A Virtualised Raspberry Pi inside a Docker image
Dockerfile
1,747
star
3

reverse-shell

Reverse Shell as a Service
JavaScript
1,732
star
4

merge-images

Easily compose images together without messing around with canvas
JavaScript
1,611
star
5

gifgen

Simple high quality GIF encoding
Shell
527
star
6

zsh-better-npm-completion

Better completion for npm
Shell
450
star
7

when-dom-ready

$(document).ready() for the 21st century
JavaScript
334
star
8

refind-ambience

Minimal theme for the rEFInd boot manager
308
star
9

humanscript

A truly natural scripting language
Shell
226
star
10

htconvert

Convert .htaccess redirects to nginx.conf redirects
JavaScript
186
star
11

browser-env

Simulates a global browser environment using jsdom
JavaScript
171
star
12

coinlist

Comprehensive list of cryptocurrencies with metadata
JavaScript
155
star
13

coinflict-of-interest

Browser extension to show user biases on Crypto Twitter.
JavaScript
144
star
14

chest

Bash glue to encrypt and hide files
Shell
129
star
15

docker-electrumx

Run an Electrum server with one command
Dockerfile
102
star
16

base64-async

Non-blocking chunked Base64 encoding
JavaScript
98
star
17

doge-seed

Dank mnemonic seed phrases
HTML
89
star
18

onionite

Explore the Tor network
JavaScript
76
star
19

window

Exports a jsdom window object.
JavaScript
74
star
20

expired

Calculate when HTTP cache headers expire
JavaScript
74
star
21

github-custom-tab-size

Chrome extension - Set custom tab size for code view on GitHub.com
JavaScript
67
star
22

howmanyconfs.com

How many confirmations are equivalent to 6 Bitcoin confirmations?
JavaScript
61
star
23

create-cert

Super simple self signed certificates
JavaScript
43
star
24

react-jsdom

Render React components to actual DOM nodes in Node.js
JavaScript
33
star
25

byte-range

Returns integer ranges for C data types
JavaScript
32
star
26

parcel-plugin-ogimage

Set absolute URL for og:image meta tags.
JavaScript
22
star
27

build-output-script

Builds a P2PKH Bitcoin transaction output script
JavaScript
21
star
28

create-xpub

Create a BIP32 extended public key
JavaScript
21
star
29

onionoo-node-client

Node.js client library for the Tor Onionoo API
JavaScript
20
star
30

autoscale-do-block-storage

Autoscale Digital Ocean block storage volumes
Shell
20
star
31

my-name-is-url

Intelligent URL parser
JavaScript
17
star
32

docker-vertcoind

Run a full Vertcoin node with one command
Dockerfile
9
star
33

tippin-badge

Readme badge generator for tippin.me
HTML
8
star
34

docker-bitcoind

Run a full Bitcoin node with one command
Dockerfile
7
star
35

create-node

Converts an HTML string to a dom node
JavaScript
7
star
36

this

Traverses up the directory tree and returns the first module found
JavaScript
7
star
37

requirable

Enables a module to require itself by name
JavaScript
6
star
38

docker-ledger-sdk

Build a Ledger app with one command
Dockerfile
6
star
39

ephemeral-electrum

A quick throwaway text based Electrum instance.
Dockerfile
5
star
40

electrs-next

Docker configuration for testing the `next` branch of electrs.
Dockerfile
5
star
41

notary-node-utils

Utilities for running a notary node
Shell
5
star
42

docker-electrum-vertcoin

Run a Vertcoin Electrum server with one command
4
star
43

docker-barterdex-api

Shell
4
star
44

vainjs

A JavaScript vanity address generator
JavaScript
4
star
45

sign-release

Easy automated release signing
Shell
3
star
46

vercel-bug

JavaScript
1
star
47

test

test repo for testing git/GitHub related things
1
star
48

arrows

My custom ZSH theme
Shell
1
star
49

eslint-config-lukechilds

My personal eslint preferences
JavaScript
1
star
50

eslint-config-xo-lukechilds

My personal XO overrides
JavaScript
1
star
51

Extension

Browser extension to show user influence on Crypto Twitter.
JavaScript
1
star
52

morethan140

View and send tweets over 140 characters
JavaScript
1
star
53

b64golf

JavaScript
1
star
54

AtHash

Social text parser
JavaScript
1
star
55

pirateproxy

Proxy site for thepiratebay.org
JavaScript
1
star
56

javascript

How we like to JavasScript at Unsplash.
JavaScript
1
star
57

umbrel-apps-test-2

1
star
58

syringe

Search and inject packages from npm
JavaScript
1
star
59

blog-clj

Clojure
1
star
60

anonlytics-express

Privacy respecting analytics for express apps
JavaScript
1
star
61

tor-hs-issue-repro

Shell
1
star
62

trim

Rust
1
star
63

hyperdex-bugtracker

1
star
64

homebrew-tap

My Homebrew tap
Ruby
1
star
65

bip39-versioned

Proof of concept adding versioning to BIP39 compatible seeds
JavaScript
1
star