From 92c06e933fc8bd2e6b1027d1640d657bcf9a49a9 Mon Sep 17 00:00:00 2001 From: Rhys Evans Date: Mon, 28 Oct 2024 18:03:39 +0000 Subject: [PATCH] fix: allow sending responses with status 0 --- packages/fetch-mock/src/Route.ts | 6 ++++++ packages/fetch-mock/src/Router.ts | 7 ++++++- .../src/__tests__/FetchMock/response-construction.test.js | 7 +++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/packages/fetch-mock/src/Route.ts b/packages/fetch-mock/src/Route.ts index 85b65e99..ca9f823f 100644 --- a/packages/fetch-mock/src/Route.ts +++ b/packages/fetch-mock/src/Route.ts @@ -89,6 +89,12 @@ function isBodyInit(body: BodyInit | object): body is BodyInit { } function sanitizeStatus(status?: number): number { + if (status === 0) { + // we do this here for now because we can't construct a Response with status 0 + // we overwrite to 0 later in the proxy wrapper around teh response. + return 200; + } + if (!status) { return 200; } diff --git a/packages/fetch-mock/src/Router.ts b/packages/fetch-mock/src/Router.ts index be3af6c9..bd5f8660 100644 --- a/packages/fetch-mock/src/Router.ts +++ b/packages/fetch-mock/src/Router.ts @@ -70,7 +70,7 @@ function shouldSendAsObject(responseInput: RouteResponseData): boolean { // TODO improve this... make it less hacky and magic if ( responseConfigProps.some( - (prop) => (responseInput as RouteResponseConfig)[prop], + (prop) => prop in (responseInput as RouteResponseConfig), ) ) { if ( @@ -268,6 +268,11 @@ export default class Router { return false; } } + + if (responseInput.status === 0) { + if (name === 'status') return 0; + if (name === 'statusText') return ''; + } // TODO fix these types properly //@ts-expect-error TODO probably make use of generics here if (typeof response[name] === 'function') { diff --git a/packages/fetch-mock/src/__tests__/FetchMock/response-construction.test.js b/packages/fetch-mock/src/__tests__/FetchMock/response-construction.test.js index 15fae2d8..98f24269 100644 --- a/packages/fetch-mock/src/__tests__/FetchMock/response-construction.test.js +++ b/packages/fetch-mock/src/__tests__/FetchMock/response-construction.test.js @@ -27,6 +27,13 @@ describe('response construction', () => { ); } }); + + it('should be able to send status 0', async () => { + fm.route('*', { status: 0 }); + const res = await fm.fetchHandler('http://a.com/'); + expect(res.status).toEqual(0); + expect(res.statusText).toEqual(''); + }); }); describe('string', () => {