UNPKG

1.61 kBPlain TextView Raw
1// Copyright IBM Corp. and LoopBack contributors 2017,2020. All Rights Reserved.
2// Node module: @loopback/testlab
3// This file is licensed under the MIT License.
4// License text available at https://opensource.org/licenses/MIT
5
6/*
7 * HTTP client utilities
8 */
9
10import http from 'http';
11import supertest from 'supertest';
12
13export {supertest};
14
15export type Client = supertest.SuperTest<supertest.Test>;
16
17/**
18 * Create a SuperTest client connected to an HTTP server listening
19 * on an ephemeral port and calling `handler` to handle incoming requests.
20 * @param handler
21 */
22export function createClientForHandler(
23 handler: (req: http.IncomingMessage, res: http.ServerResponse) => void,
24): Client {
25 const server = http.createServer(handler);
26 return supertest(server);
27}
28
29/**
30 * Create a SuperTest client for a running RestApplication instance.
31 * It is the responsibility of the caller to ensure that the app
32 * is running and to stop the application after all tests are done.
33 * @param app - A running (listening) instance of a RestApplication.
34 */
35export function createRestAppClient(app: RestApplicationLike) {
36 const url = app.restServer.rootUrl ?? app.restServer.url;
37 if (!url) {
38 throw new Error(
39 `Cannot create client for ${app.constructor.name}, it is not listening.`,
40 );
41 }
42 return supertest(url);
43}
44
45/*
46 * These interfaces are meant to partially mirror the formats provided
47 * in our other libraries to avoid circular imports.
48 */
49
50export interface RestApplicationLike {
51 restServer: RestServerLike;
52}
53
54export interface RestServerLike {
55 url?: string;
56 rootUrl?: string;
57}