mswjs / msw

Industry standard API mocking for JavaScript.
https://mswjs.io
MIT License
15.97k stars 519 forks source link

Proposal: Mock RSC payload #2255

Closed vitalets closed 2 months ago

vitalets commented 2 months ago

Scope

Adds a new behavior

Compatibility

Feature description

While I'm closely tracking the progress of App Router support in #1644, I have a proposal for solving that from another side:

Can MSW be adopted to mock React Server Component (RSC) payload?

I know that RSC is a binary format, but looking on RSC requests in devtools I see the following:

0:["development",[["children","(main)","children","__PAGE__",["__PAGE__",{}],"$L1",[null,"$L2"]]]]
4:I["(app-pages-browser)/./app/(main)/components/Pronunciation.tsx",["app/(main)/page","static/chunks/app/(main)/page.js"],"Pronunciation"]
5:I["(app-pages-browser)/./node_modules/next/dist/client/link.js",["app/(main)/not-found","static/chunks/app/(main)/not-found.js"],""]
...

Sometimes there are full JSON stringified values, that I use in my components and that I would like to mock.

I've tried to intercept such request and make plain string replacement -> values were mocked.

I've also checked server action requests, the response is also RSC with similar structure. For example, if server action throws an error, the status code is 500 and the body is:

0:["$@1",["development",null]]
1:E{"digest":"3685764491","message":"foo","stack":"Error: foo\n    at $$ACTION_0 (webpack-internal:///(rsc)/./app/page.tsx:64:11)\n   ....

Service worker could intercept that request and return mock with status 500 and custom error message. It allows to test such scenarios in components.

There is a RSC parser that could give more details on structure and what can be mocked in RSC payload.

In terms of MSW, I think of a separate RSC namespace like existing http and graphql. Pseudocode:

import { rsc, HttpResponse } from 'msw'

export const handlers = [
  rsc.post(
    '/pets',
    ({ request, params, cookies }) => {
      return HttpResponse.rsc(...)
    }
  )
];

What do you think?