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 |
|
10 | import http from 'http';
|
11 | import supertest from 'supertest';
|
12 |
|
13 | export {supertest};
|
14 |
|
15 | export 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 | */
|
22 | export 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 | */
|
35 | export 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 |
|
50 | export interface RestApplicationLike {
|
51 | restServer: RestServerLike;
|
52 | }
|
53 |
|
54 | export interface RestServerLike {
|
55 | url?: string;
|
56 | rootUrl?: string;
|
57 | }
|