UNPKG

@opra/testing

Version:
64 lines (63 loc) 2.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.TestBackend = void 0; const tslib_1 = require("tslib"); const node_http_1 = require("node:http"); const path = tslib_1.__importStar(require("node:path")); const client_1 = require("@opra/client"); const api_expect_js_1 = require("./api-expect/api-expect.js"); /** * * @class TestBackend */ class TestBackend extends client_1.FetchBackend { constructor(app, options) { super(options?.basePath ? path.join('http://tempuri.org', options.basePath) : 'http://tempuri.org', options); this._server = app instanceof node_http_1.Server ? app : (0, node_http_1.createServer)(app); } send(req) { return new Promise((resolve, reject) => { const url = new URL(req.url); // Set protocol to HTTP url.protocol = 'http'; // Apply original host to request header if (url.host !== 'opra.test' && req.headers.get('host') == null) req.headers.set('host', url.host); new Promise(subResolve => { if (this._server.listening) subResolve(); else this._server.listen(0, '127.0.0.1', () => subResolve()); }) .then(() => { const address = this._server.address(); url.host = '127.0.0.1'; url.port = address.port.toString(); return fetch(url.toString(), req); }) .then(res => { if (!this._server.listening) return resolve(res); this._server.once('close', () => resolve(res)); this._server.close(); this._server.unref(); }) .then() .catch(error => { if (!this._server.listening) return reject(error); this._server.once('close', () => reject(error)); this._server.close(); this._server.unref(); }); }); } createResponse(init) { const response = new client_1.HttpResponse(init); response.expect = new api_expect_js_1.ApiExpect(response); return response; } } exports.TestBackend = TestBackend;