fetch-light-my-request
Version:
fetch-mock wrapper over light-my-request
60 lines • 2.15 kB
JavaScript
import { inject } from "light-my-request";
import { defaultFetchMockConfig, FetchMock } from "fetch-mock";
/**
* Create a [FetchMock] from a light-my-request dispatch function.
*
* [FetchMock]: https://www.wheresrhys.co.uk/fetch-mock/docs
*/
export function createFetchMockLightMyRequest(dispatchFunc, opts = {}) {
const fetchMock = new FetchMock({ ...defaultFetchMockConfig });
fetchMock.route("*", async (callLog) => {
const res = await inject(dispatchFunc, {
url: callLog.url,
method: callLog.options.method,
headers: callLog.options.headers,
payload: callLog.options.body ?? undefined,
remoteAddress: opts.remoteAddress,
server: opts.server,
signal: callLog.options.signal ?? undefined,
});
return new Response(res.body, {
status: res.statusCode,
statusText: res.statusMessage,
headers: res.headers,
});
});
return fetchMock;
}
/**
* Create a mock fetch function (Directly returning the `FetchMock.fetchHandler`) from a
* light-my-request dispatch function.
*/
export function createFetchLightMyRequest(dispatchFunc, opts = {}) {
const fetchMock = createFetchMockLightMyRequest(dispatchFunc, opts);
return fetchMock.fetchHandler.bind(fetchMock);
}
/**
* Create a [FetchMock] from a Fastify server.
*
* [FetchMock]: https://www.wheresrhys.co.uk/fetch-mock/docs
*/
export function createFetchMockLightMyRequestFromFastify(instance, opts = {}) {
return createFetchMockLightMyRequest((req, res) => {
instance.ready((err) => {
if (err) {
res.emit("error", err);
return;
}
instance.routing(req, res);
});
}, opts);
}
/**
* Create a mock fetch function (Directly returning the `FetchMock.fetchHandler`) from Fastify
* server.
*/
export function createFetchLightMyRequestFromFastify(instance, opts = {}) {
const fetchMock = createFetchMockLightMyRequestFromFastify(instance, opts);
return fetchMock.fetchHandler.bind(fetchMock);
}
//# sourceMappingURL=index.js.map