Msw: server-side behavior in NextJS

Created on 30 Aug 2020  路  4Comments  路  Source: mswjs/msw

Describe the bug

When adding response patching to an api endpoint which is called on the server-side of NextJS it throws an error.

Environment

  • msw: ^0.20.4
  • nodejs: v10.15.2
  • npm: 6.4.1

Chrome: 84.0.4147.135

Please also provide your browser version.

To Reproduce

Steps to reproduce the behavior:

  1. Checkout this repository and follow the steps in the readme: https://github.com/hauptrolle/nextjs-msw-response-patching-bug

Expected behavior

The response should be patched without an error.

rest bug

Most helpful comment

This issue was resolved in [email protected]. Could you please update and let us know if it's fixed for you? Thanks.

All 4 comments

Hi @hauptrolle thanks for raising this 馃槃

The issue happens when fetch is called using the mocked request. When the request is of type GET or HEAD the body should be set to null when useFetch is called.

To do this the following diff should be enough

diff --git a/src/context/fetch.ts b/src/context/fetch.ts
index 7265c94..58ee629 100644
--- a/src/context/fetch.ts
+++ b/src/context/fetch.ts
@@ -43,10 +43,18 @@ export const fetch = <ResponseType = any>(
   }

   const { body } = input
-  const compliantReq: RequestInit = augmentRequestInit({
+
+  const requestParameters: RequestInit = {
     ...input,
-    body: typeof body === 'object' ? JSON.stringify(body) : body,
-  })
+    body: null,
+  }
+
+  if (input.method !== 'GET' && input.method !== 'HEAD') {
+    requestParameters.body =
+      typeof body === 'object' ? JSON.stringify(body) : body
+  }
+
+  const compliantReq: RequestInit = augmentRequestInit(requestParameters)

   return gracefully<ResponseType>(useFetch(input.url.href, compliantReq))
 }

To you want to work on a PR 馃槃 ? We nee also a test for this. You contribution will be awesome 馃挴

@marcosvega91 Cool! Thank you for your fast feedback. Sure, I can work on a MR :) Will finish it probably around tomorrow in the evening. 馃憢

It's not a problem, thanks again for the support 鉂わ笍

This issue was resolved in [email protected]. Could you please update and let us know if it's fixed for you? Thanks.

Was this page helpful?
0 / 5 - 0 ratings