What is test-listen?
The 'test-listen' npm package is a utility that helps in testing HTTP servers by providing a way to start a server and get its URL. This is particularly useful for integration tests where you need to make HTTP requests to a server.
What are test-listen's main functionalities?
Start a server and get its URL
This feature allows you to start an HTTP server and get its URL, which can then be used for making HTTP requests in your tests.
const testListen = require('test-listen');
const http = require('http');
const server = http.createServer((req, res) => {
res.end('Hello World');
});
testListen(server).then(url => {
console.log(`Server is running at ${url}`);
});
Other packages similar to test-listen
supertest
Supertest is a popular library for testing HTTP servers. It provides a high-level abstraction for testing HTTP, making it easy to send requests and assert responses. Unlike 'test-listen', which focuses on starting a server and getting its URL, Supertest provides a more comprehensive set of tools for making assertions on HTTP responses.
nock
Nock is a library for HTTP mocking and expectations. It allows you to intercept HTTP requests and provide predefined responses, making it useful for testing HTTP clients. While 'test-listen' is used for starting a server and getting its URL, Nock is used for mocking HTTP requests and responses.
http-server
http-server is a simple, zero-configuration command-line HTTP server. It is useful for serving static files and testing static websites. Unlike 'test-listen', which is used for starting a server programmatically and getting its URL, http-server is more focused on serving static content from the command line.
test-listen
URLs with ephemeral ports. async
/await
ready.
Usage
Install it:
npm install --save-dev test-listen
Pass a http.Server
to test-listen
and it will return an URL in the format http://localhost:{port}
.
The second parameter can optionally be a hostname to return in the URL
instead of localhost
.
Useful for running HTTP server testsuites:
const http = require('http');
const listen = require('test-listen');
const srv = http.createServer((req, res) => res.end('1'))
const srv2 = http.createServer((req, res) => res.end('2'))
test('urls', async t => {
let url = await listen(srv)
t.ok(url == 'http://localhost:11401')
let url = await listen(srv2)
t.ok(url == 'http://localhost:42333')
})
Authors