/* eslint-disable @typescript-eslint/no-non-null-assertion */ import express from 'express'; import * as http from 'http'; import type {AddressInfo} from 'net'; import {expect} from 'chai'; export type FakeAppServer = { url: undefined | URL; handler: (req: express.Request, res: express.Response) => void; server: undefined | http.Server; }; // To use the fake server, replace its handler with a function that // implements your test expectations. export async function newFakeAppServer(path: string): Promise { const fakeAppServer: FakeAppServer = { url: undefined, handler: (_0: express.Request, _1: express.Response) => { throw new Error('programmer error, set this function'); }, server: undefined, }; const app = express(); app.use(express.json()); app.use( path, ( req: express.Request, res: express.Response, next: express.NextFunction, ) => { fakeAppServer.handler(req, res); next(); }, ); await new Promise(resolve => { fakeAppServer.server = app.listen( { port: 0, host: '127.0.0.1', // using 'localhost' can return an ipv6 address }, () => resolve(), ); expect(fakeAppServer.server).to.be.an.instanceOf(http.Server); }); const serverAddress: AddressInfo = ( fakeAppServer.server as http.Server ).address() as AddressInfo; fakeAppServer.url = new URL(`http://${serverAddress.address}`); fakeAppServer.url.port = serverAddress.port.toString(); return fakeAppServer; } export function s(obj: unknown) { return JSON.stringify(obj, null, 1).replace(/\n/g, ''); }