You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Extracting server page logic would be an alternative, but I think that would also significantly reduce the purpose of RTL if that were to become an encouraged architectural default.
Reacted by Alejandro Martínez, Richard, 3gwebtrain, Bernardo Gomes, Sander, Danny Lopez, 박창준, Adam Goldsmith, Mohamed Abbas, Martynas Skučas and 2 more
It's render that's giving the issue. To provide the full error message:
'Page' cannot be used as a JSX component.
Its return type 'Promise<Element>' is not a valid JSX element.
Type 'Promise<Element>' is missing the following properties from type 'ReactElement<any, any>': type, props, keyts(2786)
Reacted by Alejandro Martínez, Sonali Gupta and Adam Goldsmith
I'll wait for a moderator to close this but it would be nice to have async components supported inside render
I like this idea personally. It should be easy enough to introspect if a component is async by determining if it returns a Promise. Then we can await the Promise internally and either return a Promise in render or poll to return synchronously.
Reacted by Giorgio Polvara, Flavio Silva, Anna Malchow-Perryman, Ajeet Chaulagain, cgero.eth and codewithbugs01
On a side note, even if we make this work, there's the issue of Next layout composition. If I render a Page component in my test, I most likely want to render also its layout(s). I understand this is not necessarily a concern that RTL should have, but we should keep it in mind. Next could provide an API for testing that builds the whole rendering tree.
Reacted by Nicky McCurdy, Remy, Scott, Kristiyan Dzhakov, divisandeep94, Neil Puttick (N), Luciano Amâncio, Ariel Sardinha, asim-headout, Maurice Webb and 1 more
We could document using layouts similarly to how we already document using providers: by importing them and passing them as the wrapper option of render.
@Gpx has a good point that rendering nested layouts would be more challenging. We could try to expose an abstraction, but the paths to import from would be dynamic and depend on Next patterns. If this isn't practical, we can open an issue with Next upstream and ask for an API to consume internally.
Also if we change render to be compatible with returning promises, we should probably ship a breaking change so end users are aware they may need to change their tests (especially if they're using TypeScript).
Reacted by Giorgio Polvara, Remy, Alex Krolick, Jacky Wijaya, Teodoro Pedro, ggFROOK and 3gwebtrain
I agree we should ask Next to provide an API. I'm thinking something like this:
constRSC=routeComponent('/some/path')// This will return an RSC with all nested layouts passing the correct propsrender(RSC)// With additional propsconstRSC=routeComponent('/some/path',{foo: 1})render(RSC)
WDYT?
As for the breaking change, won't this be a feature? I don't think anyone was relying on render breaking for async components.
I'm doing more research into RSCs using Next, and I noticed some mistaken assumptions I had:
Determining if a component uses suspense is not possible due to the halting problem as it would be valid for the component to sometimes not return a Promise, and we can't distinguish between a component not returning a Promise currently vs. ever.
The new rendering async APIs don't return Promises, they return streams. So, we don't necessarily need to make our render function async, though we may need to poll to unwrap streams synchronously.
Overall, I think supporting React server components involves figuring out the following concerns:
Figuring out how we can internally render async components (may involve using a different render API, and would require using experimental/canary React right now)
I agree we should ask Next to provide an API. I'm thinking something like this:
constRSC=routeComponent('/some/path')// This will return an RSC with all nested layouts passing the correct propsrender(RSC)// With additional propsconstRSC=routeComponent('/some/path',{foo: 1})render(RSC)
WDYT?
@Gpx Shouldn't that be render(<RSC />)? Also are you suggesting the URL path or filesystem path here?
The idea to render the server component as async client components seems to be the best idea I've seen so far.
I don't think it's suitable for RTL to bake Next.js' (or any other framework's) semantics into it's API. Async client components solve this by being agnostic of any framework.
I think this would retain the current RTL API with maybe the addition of a suspense wrapper - rendering nothing initially could be confusing so enforcing a fallback makes sense.
render(<Page/>)// throws an error because there's no boundary (I think this would be default react behaviour)render(<Suspense><Page/></Suspense>)// This would be ok
This is a good workaround if the Children are sync, if the children are async you get this:
async/await is not yet supported in Client Components, only Server Components. This error is often caused by accidentally adding 'use client' to a module that was originally written for the server.
A component suspended inside an act scope, but the act call was not awaited. When testing React components that depend on asynchronous data, you must await the result:
await act(() => ...)
Unable to find an element with the text: server. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
@tarunsahnan thank you so much for this, it worked perfectly. I made one small update to allow the ability to pass in testing-library/react options 👍 (gist)
@sroebert oh I missed you were the original author. This is a long thread 😅 we are still working on react 19 upgrade. Thank you for this, happy to know it has a solve when we migrate
Yeah tried to find a way around that, so far have not succeeded as it is baked into the React code. Guess there are very hacky ways, but those have their own drawbacks.
I had some helpful suggestions from the React team on how to start up an RSC server with full support for React RSC features (excluding Next specific features for now). I'm developing a renderServer function that simulates a React server with our existing React client.
You can test most async components with React 18.3 (canary) or 19 (rc):
import { render, screen } from "@testing-library/react";
import { Suspense } from "react";
import Page from "./page";
test("Page", async () => {
render(
,
);
await screen.findBy...(...); // first assertion must await for suspense
// additional assertions may follow
});
You may want to use a custom render function to simplify test setup if your suite heavily relies on async components.
If you need other RSC (i.e. server actions) or app router (i.e. layouts) features you can use hard coding, mocks, or an e2e test framework until we figure out these issues.
server-only errors
Some React Server Components import the server-only module to prevent accidental usage in Client Components, resulting in this error:
This module cannot be imported from a Client Component module. It should only be used from a Server Component.
React Testing Library doesn't have a server yet, so it needs to render Server Components in its client for now.
If you're using Jest or Vitest, you can disable the module's error with an empty mock script named __mocks__/server-only.
With Vitest, you'll also need to manually register it:
vi.mock("server-only");
Alternatively you can mock the module in a setup or test file, for example:
Use typescript@^5.1.2 and @types/react@^18.2.8 to fix this error when rendering async components:
'...' cannot be used as a JSX component. Its return type 'Promise' is not a valid JSX element. Type 'Promise' is missing the following properties from type 'ReactElement<any, any>': type, props, key
React warnings
Newer versions of React 18.3 (canary) and 19 (rc) added warnings when rendering server components in clients:
Warning: async/await is not yet supported in Client Components, only Server Components
Warning: A component was suspended by an uncached promise. Creating promises inside a Client Component or hook is not yet supported, except via a Suspense-compatible library or framework.
However, tests following my suggestions should still work for now. I believe the warning mainly exists to prevent accidental usage of async components without a meta framework and inform users about potential instability. Remember to pin your React version in a shared package.json or lockfile though, as changes in canaries and rcs could be breaking.
It handles all cases of testing RSC, like nested async components and components using use, and I prefer to use this method rather than a custom workaround.
However, it still does not work with the React 19 release, i.e:
At storybook, we have been investigating this problem for some time as well.
In the past we also have used the "render RSC as async client component" workaround as discussed here.
We have been discussing better ways with @eps1lon and @mattcarrollcode from the react team.
The main problem is to entangle the mix of environments:
render(<Page/>)//^^^^^^^^^^^^^^^^ should probably run on the server expect(screen....).ToBe(....)//^^^^^^^^^^^^^^^^ is this supposed to use the DOM i.e. run in a browser?
Jest has a way to test Node.js code in isolation with @jest-environment node which works fine for testing SSR output or RSC output. Jest also has a way to test client side like @jest-environment jsdom which works fine to test client-only rendering of components.
The problem is that there's no way for the same test two spawn both - and get the right export conditions set up in the module resolution. You can hack around it in various ways by setting up an environment that tries to be both but it won't test exactly the right thing and a key feature of RSC is that "server-only" and "client-only" can be mutually exclusive environments and we can have the same code run differently in each one.
To do this properly we need test runners (vitest too ideally) to adopt a way to run two environments for a single test so you can run RSC, SSR, hydrate it and assert on the result.
The test will run both environments in one (browser-like) runtime, but because of a seperate react-server environment, we can make sure that the server component tree can be serialized to react flight data with:
the correct export conditions in the module resolution (react-server)
and server specific transformations.
I am working on an experiment with that you can try out here: https://github.com/kasperpeulen/vitest-plugin-rsc
We plan to use this in storybook for our vite specific builders and our addon-vitest that uses vitest as storybook test runner.
To use it in vitest directly, you will need to register the vitest plugin and use vitest browser mode for now:
// vitest.config.tsimport{defineConfig}from"vitest/config";// 👇 not yet released, clone the package for now to try it outimportvitestPluginRSCfrom"vitest-plugin-rsc";exportdefaultdefineConfig({plugins: [vitestPluginRSC()],test: {browser: {enabled: true,provider: "playwright",instances: [{browser: "chromium"}],},setupFiles: ["./src/vitest.setup.ts"],},});
Setup the runtime:
// src/vitest.setup.tsimport{beforeAll,beforeEach}from"vitest";import{cleanup,setupRuntime}from"vitest-plugin-rsc/testing-library";beforeAll(()=>{setupRuntime();// ⬅️ spins up the RSC runtime});beforeEach(async()=>{awaitcleanup();// ⬅️ reset DOM between tests});
And then you can write test like this:
import{expect,test,screen}from"vitest";import{renderServer}from"vitest-plugin-rsc/testing-library";import{userEvent}from"@testing-library/user-event";import{http}from"msw";import{Users}from"./users";import{api}from"../lib/api";import{getLikes}from"../lib/db";import{msw}from"../test/msw";test("increments likes on click",async()=>{msw.use(http.get(api("/users"),()=>Response.json([{id: 5,name: "Ada"}])),);awaitrenderServer(<Users/>,{rerenderOnServerAction: true});expect(awaitgetLikes(5)).toBe(0);awaituserEvent.click(awaitscreen.findByRole("button",{name: /toggle/i}));awaituserEvent.click(awaitscreen.findByRole("button",{name: /like/i}));expect(awaitscreen.findByText("+1")).toBeVisible();expect(awaitgetLikes(5)).toBe(1);});
Vitest plugin with 2 environments
The implementation of renderServer funciton simply serializes the server component tree to react flight data with renderToReadableStream and then deserializes it back to JSX with createFromReadableStream:
import{renderToReadableStream}from"@vitejs/plugin-rsc/react/rsc";// 👇 this is imported with a helper, to get the correct export conditions in the module resolutionconst{ createFromReadableStream }=awaitimportReactClient("@vitejs/plugin-rsc/react/browser");// serializeconstflightStream=renderToReadableStream(<ServerComponent/>);// deserializeconstjsx=awaitcreateFromReadableStream(flightStream);
The vitest plugins spawns 2 environments.
The react-server environment is a client environment, but has the react-server condition applied, to serialize server components with right module resolution and some server specific transformation to turn client components into references.
A second client environment react_client is created that to render the client components marked with use client, deserialize the flight stream and to render the JSX to the dom.
Transformations
The transformations of the vite plugin will make sure that for a client import in the server tree like:
For now I have copied over the specific transformations I needed from the RSC plugin from @hi-ogawa, as the specific stuff I needed was not included in the exports of the plugin.
Vite Environment API
I'm quite unsure about if I use the environment API correctly here. I simply made a new import helper:
However, hot module reload doesn't work in this way, and the plugin also seem to mess up browser module mocking somehow.
I hope to get some guidance from the vite team here.
Nextjs example
For example, I tried to make a nextjs example with module mocking:
import{describe,expect,test,vi}from"vitest";import{renderServer}from"vitest-plugin-rsc/testing-library";import{screen}from"@testing-library/dom";importAuthButtonfrom"./auth-button.tsx";import{RequestCookiesAdapter}from"next/dist/server/web/spec-extension/adapters/request-cookies";import{RequestCookies}from"next/dist/compiled/@edge-runtime/cookies";import{getUser}from"../lib/session.ts";vi.mock(import("../lib/session"),{spy: true});vi.mock("next/headers",()=>({cookies: async()=>RequestCookiesAdapter.seal(newRequestCookies(newHeaders())),}));test("renders add button when logged in",async()=>{vi.mocked(getUser).mockReturnValue("some-user");awaitrenderServer(<AuthButtonnoteId={null}>Add</AuthButton>);expect(awaitscreen.findByRole("menuitem",{name: /Add/})).toBeVisible();});
This works correctly the first run, but the mocks are not applied anymore in a second test run.
Especially for nextjs support, getting module mocking working seems essential to mock apis like: cookies, headers, redirect and revalidatePath
Direction forward
Although there are some rough edges, I think this is the best way forward for unit-testing/component testing RSC's.
Running both the server and client in the same runtime, might seem weird at first, I think it is the only way to get a unit test like experience.
In a unit test, you want to be able to run any function or component in the unit test, not only specific routes.
You also want to easily mock globals, time, http, modules, fs etc.
For example, in this approach, you can mock the date in the backend and frontend with a simple line before your test:
test('allows purchases within business hours',()=>{// set hour within business hoursconstdate=newDate(2000,1,1,13)vi.setSystemTime(date)awaitrenderServer(<PurchaseItem/>);})
Or mock out http endpoints (both in the backend and client):
At this moment, I only got it working with vitest browser mode, not yet with jsdom.
It might seem useful to run it in jsdom, as RSC often run in node as well.
Personally, I think that is very useful to get visual feedback of your react components in vitest or storybook.
Also it is easier to mock our node correctly, than mock out the browser correctly.
Especially, because in modern code people often use web based API's in the RSC components such as: fetch, Headers, Request, Response, crypto, TextEncoder, TextDecoder, URL, Blob, File, FormData, atob, btoa, ReadableStream,
Reacted by Phil Wolstenholme, Menachem Hornbacher, Chris Chudzicki, Danilo Fuchs, Abel Castro, Nicky McCurdy and Simon Baruffaldi
Reacted by Maxime Richard, Tom Coleman, Valentin Palkovic, bmth, Noah Baldwin, Michal Obrocnik, Armand Abric, Phil Wolstenholme, Gary Forster, Michael Shilman and 14 more
Reacted by Michael Shilman, Armand Abric, Phil Wolstenholme and Menachem Hornbacher
Reacted by Tarek Touati, Phil Wolstenholme, Menachem Hornbacher and Shogo Fukami
I remember 15 years ago in asp.net webforms where code was difficult to test. This reminds me of that. But now it's 2025, and I've spent 2 hours on this. ... and of course the "solution" doesn't work.
I built nextcov to solve this exact problem. It uses V8 coverage via CDP instead of Istanbul instrumentation, so it works with SWC/Next.js 15 server components without Babel. Collects both client and server coverage from Playwright E2E tests and merges with Vitest unit coverage. Check it out: https://github.com/stevez/nextcov
This is a hacky function to test async server components by awaiting Suspense components. You can call it like this:
import{test}from"vitest";test("Async Component Render",async({ expect })=>{constpage=Page()// or <Page /> or any other async function;const{ getByTestId, container }=awaitasyncRender(page);expect(getByTestId("something-to-test")).toBeDefined()});
The gist of the program is here. The procedure is to:
stream the component to a string using the renderToPipeableStream Server API service compatible with React 19.
and render that string dangerously to HTML.
import{pipe}from"fp-ts/lib/function.js"// or from any other piping mechanism;exportconstasyncRender=async(component: Promise<React.ReactElement>)=>pipe(component,streamComponentToString,renderStringToHTML);
Notes:
Using Vitest for testing and works in Next.JS with Server Actions and cacheComponents enabled.
Hacky comes from the fact that I'm going back and forth between html to string to html. This is because I'm streaming the async server component to a string. I'm sure there is a better way to accomplish this.
This is awaiting all Suspense components. I'm pretty sure using renderToPipeableStream is the only way to do so according to the React docs. Awaiting all Suspense components could hang so there is an optional timeout of 10000ms baked into
the streamComponentToString function.
As a reminder, this is just rendering the streamed text on the server. Any testing of interactivity is impossible. Test client components directly from the client. This is just to be used if promised content indeed lands on the page.
Full code:
importReactfrom"react";import{pipe}from"fp-ts/lib/function.js";import{renderToPipeableStream}from"react-dom/server";import{Writable}from"node:stream";import{render}from"@testing-library/react";exportfunctionstreamComponentToString(component: Promise<React.ReactElement>,){returnnewPromise<string>((resolve,reject)=>{lethtmlBuffer="";constwritableStream=newWritable({write(chunk,encoding,callback){htmlBuffer+=chunk.toString();callback();},});const{ pipe, abort }=renderToPipeableStream(component,{onAllReady(){try{pipe(writableStream);}catch(error){reject(error);}},onShellError(error){reject(error);},onError(error){console.error("React rendering error captured:",error);},});writableStream.on("finish",()=>{resolve(htmlBuffer);});writableStream.on("error",(error)=>{reject(error);});// Optional: Setup a fail-safe timeout to abort hanging requestsconstTIMEOUT_MS=10000;setTimeout(()=>{abort();},TIMEOUT_MS);});}exportasyncfunctionrenderStringToHTML(htmlPromise: Promise<string>){consthtml=awaithtmlPromise;returnrender(<divdata-testid="test-wrapper"dangerouslySetInnerHTML={{__html: html}}/>);}exportconstasyncRender=async(component: Promise<React.ReactElement>)=>pipe(component,streamComponentToString,renderStringToHTML);
If this helps anyone, I can make a more polished final form of the function.
Activity
prakashtiwaari commentedon May 11, 2023
You can use like this:
remy90 commentedon May 11, 2023
@prakashtiwaari Not quite.
It's
renderthat's giving the issue. To provide the full error message:remy90 commentedon May 11, 2023
A friend came up with the following:
I'll wait for a moderator to close this but it would be nice to have async components supported inside render
eps1lon commentedon May 11, 2023
nickserv commentedon May 13, 2023
I like this idea personally. It should be easy enough to introspect if a component is async by determining if it returns a Promise. Then we can await the Promise internally and either return a Promise in render or poll to return synchronously.
Gpx commentedon May 14, 2023
For those that are trying to mock API responses, this seems to be working for now:
If you don't define
global.fetch, you getReferenceError: fetch is not defined.I would love to be able to use MSW, but that's still not working with Next's model. See: https://twitter.com/ApiMocking/status/1656249306628915208?s=20
On a side note, even if we make this work, there's the issue of Next layout composition. If I render a
Pagecomponent in my test, I most likely want to render also its layout(s). I understand this is not necessarily a concern that RTL should have, but we should keep it in mind. Next could provide an API for testing that builds the whole rendering tree.nickserv commentedon May 15, 2023
We could document using layouts similarly to how we already document using providers: by importing them and passing them as the
wrapperoption ofrender.@Gpx has a good point that rendering nested layouts would be more challenging. We could try to expose an abstraction, but the paths to import from would be dynamic and depend on Next patterns. If this isn't practical, we can open an issue with Next upstream and ask for an API to consume internally.
Also if we change render to be compatible with returning promises, we should probably ship a breaking change so end users are aware they may need to change their tests (especially if they're using TypeScript).
Gpx commentedon May 15, 2023
I agree we should ask Next to provide an API. I'm thinking something like this:
WDYT?
As for the breaking change, won't this be a feature? I don't think anyone was relying on
renderbreaking for async components.nickserv commentedon May 15, 2023
I'm doing more research into RSCs using Next, and I noticed some mistaken assumptions I had:
renderfunction async, though we may need to poll to unwrap streams synchronously.Overall, I think supporting React server components involves figuring out the following concerns:
nickserv commentedon May 15, 2023
@Gpx Shouldn't that be
render(<RSC />)? Also are you suggesting the URL path or filesystem path here?tom-sherman commentedon May 15, 2023
The idea to render the server component as async client components seems to be the best idea I've seen so far.
I don't think it's suitable for RTL to bake Next.js' (or any other framework's) semantics into it's API. Async client components solve this by being agnostic of any framework.
I think this would retain the current RTL API with maybe the addition of a suspense wrapper - rendering nothing initially could be confusing so enforcing a fallback makes sense.
nickserv commentedon May 16, 2023
tom-sherman commentedon May 16, 2023
nickserv commentedon May 16, 2023
tom-sherman commentedon May 16, 2023
137 remaining items
baldwinn-anz commentedon Mar 7, 2025
Perhaps for
async FC > async FC, but not forclient FC > async FCnascjoao commentedon Mar 18, 2025
At the moment, I have had success using this:
instead of this:
I'm using Next 15 which comes with React 19.
DanielHoernerNuernberger commentedon Apr 17, 2025
This is a good workaround if the Children are sync, if the children are async you get this:
if you do something like this:
await act(async () => { render( await Page({ params: Promise.resolve({ something: "abc" }), }), ) await screen.findByRole("heading", { name: "Best Title", }) })you get:
JasonMore commentedon Apr 25, 2025
@tarunsahnan thank you so much for this, it worked perfectly. I made one small update to allow the ability to pass in testing-library/react
options👍 (gist)sroebert commentedon Apr 26, 2025
Good to see other people using my original code with success.
After upgrading to React 19, I had to make some changes to it. The updated version of the original gist, working with React 19, can be found here: https://gist.github.com/sroebert/a04ca6e0232a4a60bc50d7f164f101f6
JasonMore commentedon Apr 26, 2025
@sroebert oh I missed you were the original author. This is a long thread 😅 we are still working on react 19 upgrade. Thank you for this, happy to know it has a solve when we migrate
f1yingbanana commentedon May 29, 2025
This seems to be throwing some invalid hook call warnings. Harmless but pollutes the output somewhat 🦖
sroebert commentedon May 29, 2025
Yeah tried to find a way around that, so far have not succeeded as it is baked into the React code. Guess there are very hacky ways, but those have their own drawbacks.
aurorascharff commentedon Jul 18, 2025
I'm still using this method with the following React versions:
It handles all cases of testing RSC, like nested async components and components using
use, and I prefer to use this method rather than a custom workaround.However, it still does not work with the React 19 release, i.e:
Any insight here?
kasperpeulen commentedon Jul 26, 2025
At storybook, we have been investigating this problem for some time as well.
In the past we also have used the "render RSC as async client component" workaround as discussed here.
We have been discussing better ways with @eps1lon and @mattcarrollcode from the react team.
The main problem is to entangle the mix of environments:
As @sebmarkbage said earlier:
However, with the new vite environment API (https://vite.dev/guide/api-environment) and the release of the vite rsc plugin (https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-rsc) we have an interesting opportunity to do exactly that, create 2 vite environments for a single vitest tests!
The test will run both environments in one (browser-like) runtime, but because of a seperate
react-serverenvironment, we can make sure that the server component tree can be serialized to react flight data with:react-server)I am working on an experiment with that you can try out here:
https://github.com/kasperpeulen/vitest-plugin-rsc
We plan to use this in storybook for our vite specific builders and our addon-vitest that uses vitest as storybook test runner.
To use it in vitest directly, you will need to register the vitest plugin and use vitest browser mode for now:
Setup the runtime:
And then you can write test like this:
Vitest plugin with 2 environments
The implementation of
renderServerfunciton simply serializes the server component tree to react flight data withrenderToReadableStreamand then deserializes it back to JSX withcreateFromReadableStream:The vitest plugins spawns 2 environments.
clientenvironment, but has thereact-servercondition applied, to serialize server components with right module resolution and some server specific transformation to turn client components into references.react_clientis created that to render the client components marked withuse client, deserialize the flight stream and to render the JSX to the dom.Transformations
The transformations of the vite plugin will make sure that for a client import in the server tree like:
Is transformed to a reference:
For now I have copied over the specific transformations I needed from the RSC plugin from @hi-ogawa, as the specific stuff I needed was not included in the exports of the plugin.
Vite Environment API
I'm quite unsure about if I use the environment API correctly here. I simply made a new import helper:
And a server handler to resolve the import with the right conditions and transformations:
However, hot module reload doesn't work in this way, and the plugin also seem to mess up browser module mocking somehow.
I hope to get some guidance from the vite team here.
Nextjs example
For example, I tried to make a nextjs example with module mocking:
This works correctly the first run, but the mocks are not applied anymore in a second test run.
Especially for nextjs support, getting module mocking working seems essential to mock apis like:
cookies,headers,redirectandrevalidatePathDirection forward
Although there are some rough edges, I think this is the best way forward for unit-testing/component testing RSC's.
Running both the server and client in the same runtime, might seem weird at first, I think it is the only way to get a unit test like experience.
In a unit test, you want to be able to run any function or component in the unit test, not only specific routes.
You also want to easily mock globals, time, http, modules, fs etc.
For example, in this approach, you can mock the date in the backend and frontend with a simple line before your test:
Or mock out http endpoints (both in the backend and client):
Using vitest browser mode
At this moment, I only got it working with vitest browser mode, not yet with jsdom.
It might seem useful to run it in jsdom, as RSC often run in node as well.
Personally, I think that is very useful to get visual feedback of your react components in
vitestorstorybook.Also it is easier to mock our node correctly, than mock out the browser correctly.
Especially, because in modern code people often use web based API's in the RSC components such as:
fetch,Headers,Request,Response,crypto,TextEncoder,TextDecoder,URL,Blob,File,FormData,atob,btoa,ReadableStream,The filesystem is easily mocked out with an in-memory file system:
https://vitest.dev/guide/mocking.html#file-system
Which is in general a good practice; to isolate your unit tests from IO.
And even for databases there are many browser friendly in-memory implementations:
https://github.com/morintd/prismock
https://github.com/oguimbal/pg-mem
kudorgyozo commentedon Oct 30, 2025
I remember 15 years ago in asp.net webforms where code was difficult to test. This reminds me of that. But now it's 2025, and I've spent 2 hours on this. ... and of course the "solution" doesn't work.
stevez commentedon Dec 9, 2025
I built nextcov to solve this exact problem. It uses V8 coverage via CDP instead of Istanbul instrumentation, so it works with SWC/Next.js 15 server components without Babel. Collects both client and server coverage from Playwright E2E tests and merges with Vitest unit coverage. Check it out: https://github.com/stevez/nextcov
docs: sharpen README pitch and add full-loop example
sbaruffaldi commentedon Jul 23, 2026
This is a hacky function to test async server components by awaiting Suspense components. You can call it like this:
The gist of the program is here. The procedure is to:
Notes:
cacheComponentsenabled.the
streamComponentToStringfunction.Full code:
If this helps anyone, I can make a more polished final form of the function.