Open remy90 opened 1 year ago
You can use like this:
it('should render', async() => {
render(<Page />);
await waitFor(()=> {
expect(screen....).ToBe(....)
});
});
@prakashtiwaari Not quite.
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)
A friend came up with the following:
const props = {
params: { surveyType: '123' },
searchParams: { journeyId: '456' },
}
const Result = await Page(props)
render(Result)
I'll wait for a moderator to close this but it would be nice to have async components supported inside render
Once TypeScript 5.1 is out (scheduled for 30th of May) we'll land https://github.com/DefinitelyTyped/DefinitelyTyped/pull/65135 which fixes this issue.
A friend came up with the following:
const props = { params: { surveyType: '123' }, searchParams: { journeyId: '456' }, } const Result = await Page(props) render(Result)
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.
For those that are trying to mock API responses, this seems to be working for now:
test("should do stuff", async () => {
global.fetch = jest.fn().mockResolvedValue({
json: jest.fn().mockResolvedValue({ login: "Gio" }),
});
render(await Page());
expect(screen.getByText("Hi Gio!")).toBeInTheDocument();
});
If you don't define global.fetch
, you get ReferenceError: 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 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.
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
.
import {render} from '@testing-library/react'
import Layout from './layout'
import Page from './page'
render(<Page />, {wrapper: Layout})
@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).
I agree we should ask Next to provide an API. I'm thinking something like this:
const RSC = routeComponent('/some/path') // This will return an RSC with all nested layouts passing the correct props
render(RSC)
// With additional props
const RSC = 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:
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:
I agree we should ask Next to provide an API. I'm thinking something like this:
const RSC = routeComponent('/some/path') // This will return an RSC with all nested layouts passing the correct props render(RSC) // With additional props const RSC = 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
For anyone that wants to help, I'm trying to figure out why I can't hydrate into a server rendered document, it's like it's destroying the whole document. https://gist.github.com/nickmccurdy/a5797bec9bb7e1156f814846c9bcb04b https://github.com/nickmccurdy/rsc-testing
Why are you trying to server render? RSC doesn't rely on SSR, that's an optional optimisation step. See https://github.com/dai-shi/wakuwork for an example of this
You need to call createFromFetch/readable from the react-server-dom-webpack/client and pass that element to react Dom to render. This ofc relies on having access to a RSC stream which you can create from the same package.
I'd rather not add APIs specific to bundlers, especially since Next has already moved to other bundlers and we still have others to support in the future.
That isn't really a bundler specific API, it includes the shared pieces shared across all bundlers. Source.
I do think it's easier to just mount the server component as a client component with createRoot though - this works in react-dom canary today.
See commit on your test repo here: https://github.com/tom-sherman/rsc-testing/commit/9e4aa67dafae735440fb75a481c2ffc2a87671ec
I'm not sure how RTL can support rendering of the root layout in Next.js, but as I said before I don't think it should - at least not part of it's core API. The root layout returning <html>
is a Next.js-specific idiom, not all server component frameworks choose to work this way.
Thanks for the branch, that's interesting. I'd still like to understand why this works and onAllReady
doesn't though, as that's supposed to be used for SSG where having suspense fallbacks everywhere wouldn't be accessible. Also, while I understand why your version of the test needs to await for a suspended render, I'd rather not make end users worry about understanding this if there's a way to ensure certain components load automatically. Additionally, both branches still have act
warnings, though I have no idea how to fix this as I've already tried using it in various ways.
Also, while I understand why your version of the test needs to await for a suspended render, I'd rather not make end users worry about understanding this if there's a way to ensure certain components load automatically
You're going to need an await
somewhere - you can't syncronously block because it's an async component. I suppose you could have a builtin suspense boundary and have the user await render(<Page />)
but as soon as the user adds a suspense boundary somewhere they're gonna need to use waitFor anyway.
That's closer to what I was thinking originally. Though, I think I'm confused about how this is working, but I'll reply here again when I resolve it.
I agree we should ask Next to provide an API. I'm thinking something like this:
const RSC = routeComponent('/some/path') // This will return an RSC with all nested layouts passing the correct props render(RSC) // With additional props const RSC = 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?
No, I think it should be render(RSC)
where RSC is something like <Component {...nextProps} >
. Alternatively routeComponent
could return a component and its props:
const { Component, props } = routeComponent('/some/path')
render(<Component {...props} />)
We need not only the components tree but also the props that Next is passing.
The URL should be passed to the method, not the filesystem path. If we want to simulate a real user interacting with the app they'll use URLs.
To be clear, I'm not saying we should implement this in RTL, but rather that we should ask the Next team to provide it since it will be helpful for anyone doing tests.
I'm not sure we need it to return params, since you can just choose what params to render in your test by changing the URL.
I'm not sure we need it to return params, since you can just choose what params to render in your test by changing the URL.
Say you want to test the URL /foo/bar/baz
. What are the params
? Well, it depends on your file system:
Route | params |
---|---|
app/foo/[slug]/baz |
{ slug: 'bar' } |
app/foo/bar/[slug] |
{ slug: 'baz' } |
app/foo/[[...slug]] |
{ slug: ['bar', 'baz'] } |
I can create the params
object in my tests and pass it to the component, but if later I modify the filesystem, I might break my code, and my tests will still work.
If we want to keep the render(<Component />)
format rather than render(Component)
Component
could just render the tree passing the correct params
.
Do we agree that RTL (at least in the core API) shouldn't support this kind of routing stuff? If so probably best to split that conversation out into a different issue?
I agree, I'll open an issue in Next's repo
If we want to keep the
render(<Component />)
format rather thanrender(Component)
Component
could just render the tree passing the correctparams
.
@Gpx Yes, I think that's simpler, and I'd rather avoid exposing the implementation detail of param values.
Do we agree that RTL (at least in the core API) shouldn't support this kind of routing stuff? If so probably best to split that conversation out into a different issue?
@tom-sherman I'm not suggesting we add a Next specific app router API directly into Testing Library. However, I'd like us to have either docs or some sort of adapter/facade/etc. design pattern that composes a Next routing primitive.
Guys any example how i can test pages inside app/[locale] folder with providers (next-intl)? Because i am getting invariant expected app router to be mounted
This is my test file
import { render, screen } from '@testing-library/react';
import Home from '@/app/[locale]/page';
import Layout from '@/app/layout';
import Header from '@/components/header';
import { Providers } from '@/app/providers';
import Footer from '@/components/footer';
import SessionModal from '@/components/Modals/SessionModal';
import { NextIntlClientProvider } from 'next-intl';
import messages from '../messages/en.json';
describe('Home', () => {
it('renders a heading', () => {
render(
<NextIntlClientProvider locale={'en'} messages={messages}>
<Header />
<Providers>
<Home />
</Providers>
<Footer />
<SessionModal />
</NextIntlClientProvider>,
{ wrapper: Layout }
);
expect(screen.getByRole('heading')).toHaveTextContent('Let’s Get Started!');
});
});
@DonikaV Could you share a full repository or Gist that reproduces the error?
@nickmccurdy hey, no i can't but i resolved finally it, errors was because of useRouter() This helps me
jest.mock('next/navigation', () => ({
...require('next-router-mock'),
useSearchParams: () => jest.fn(),
}));
FYI request for a testing method in Next https://github.com/vercel/next.js/discussions/50479
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.
Full integration with Next's app router depends on https://github.com/vercel/next.js/discussions/50479.
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(
<Suspense>
<Page />
</Suspense>,
);
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
errorsSome 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:
jest.mock("server-only");
vi.mock("server-only", () => ({}));
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
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.
Commenting to follow this - I'm also interested in this topic. I spent some time thinking about a similar problem, "how to test Next.js SSR behavior in Cypress", of which some thoughts are documented here. I don't have a great solution yet, but am very interested in a general solution for testing components that require server behavior, which is increasingly common with SSR frameworks and innovations like RSC.
Mock/stubbing things can work for some use cases, but if the the paradigm of moving more and more things to the server side continues, I think we will need something a bit more robust and production like to write reliable tests.
I personally think Cypress is the best way to test server components in an application (Next.js or any other future RSC framework). My opinion is mostly informed by the thread and Dan's tweet here.
Cypress (with optionally mocked network calls to APIs) is the best choice because it does a proper integration test of the entire lifecycle of a component inside of your framework. So much of RSCs are implemented in the framework and router layer that you're often not testing them very well with unit tests in a fake environment.
I think though that these unit tests are valuable for library maintainers - it's not feasible for them to run integration tests for every framework that exists. Instead they can target their testing with the parts of RSC that are implemented in React. This is where RTL comes in I think, it can help to provide a nice API and DX for those component library developers.
Server rendering async components is not different to server rendering any other components. The APIs are not different (otherwise it wouldn't compose). Though I see how using renderToPipeableStream
looks unwieldy so I'll definitely try to come up with a light wrapper around it. The hard part here will be deciding on how granular the streaming aspect should be tested. Probably best to start with an approach the just waits for everything to load and then return the final result.
The initial issue description poses a much harder problem: How do we 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?
Mixing these two has a lot of pitfalls that needs carefully crafted tests and environments. We're already facing issues with this in the React codebase and don't have a good solution for it yet.
Or is the issue about testing RSC (e.g. ensuring server code like server actions only runs on the server, client code only on the client) which needs a framework. It's probably better to defer that to the frameworks itself since they also take care of e.g. ReactDOM.preload()
, ReactDOM.preinit()
or server actions. At this point you're better off using the e2e testing framework of your choice (e.g. Playwright or Cypress) because that ensures you don't accidentally test implementation details of the framework.
I personally think Cypress is the best way to test server components in an application
But what if your application is made of RSC? Won't use Cypress or other E2E lead to slow tests?
Cypress (with optionally mocked network calls to APIs) is the best choice because it does a proper integration test of the entire lifecycle of a component inside of your framework.
You can mock browser network calls but can't mock calls made by the server component. In other words, with a component like this, I can't mock the fetch
call:
export default async function Page() {
const user = await fetch('/user/1');
return <div>{user.name}</div>
}
I don't have a solution to these problems, but as of now, using E2E test is not a suitable solution for most applications.
You can use a proxy (or a stubbed fetch or API client) to accomplish the mocked network calls, hopefully Mock Service Worker will support server components in Next.js eventually to make this easier.
I agree it's not entirely practical to write an End to End test for every permutation of each RSC. That said, given:
export default async function Page() {
const user = await fetch('/user/1');
return <div>{user.name}</div>
}
If you mock fetch, what are you really testing here? Considering these components are designed to render on the server, I think we need to build some tooling that uses the server, at least in some capacity. If you stub out all the server calls, it's just a client component, at that point.
I think that RSC really do should be integrated tested, at least to to an extend, depending what your component does. If it needs to use fs
to read something, maybe using a real fs
is better - it's definitely more production like. I haven't worked with RSC in prod enough to get an idea of what kind of components people would like to test, is there any good real world resources?
Firstly, you'd want to test what happens when that fetch failed.
In the real world RSC do a lot of things at runtime:
All of these things can happen dynamically or based on some logic that you would want to test.
A lot of that is implemented inside the framework which is why an integration/e2e test is needed
I agree it's not entirely practical to write an End to End test for every permutation of each RSC
I'm not suggesting this btw, at least not for application developers. I'm suggesting performing high-fidelity tests against the framework using Cypress or similar (this is what's recommended by the React team). You would test routes not components. This makes sense to me because RSC are as much a routing solution than anything else.
I'm still researching this and interested in finding a common ground of testing APIs that would be useful for integration testing any RSC framework. Now that there are multiple attempts at adding different RSC renderers to React core, I'll try to figure out testing adapters that could work without being too tied to framework implementation details.
To some extent you can just use async functions in the client which is probably the easiest way to test it.
Ultimately, the thing blocking us from adding something really good that Just Works correctly in a unit testing running like Jest is the ability to run two different environments for one test. We have a workaround in the React repo for our own tests but it's not great we're pretty close to just ripping out Jest for our tests for this reason.
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.
This is not really a new thing, this has been an issue with isomorphic code like getServerSideProps / loaders and client code too. Bugs has slipped past like trying to access a database client-side which worked in the tests. It's just that we're trying to define and take advantage of these boundaries deeper now.
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.
It doesn't have to be a full E2E integration but having the ability to run two environments would allow us to build official lightweight bindings for rendering React in that environment. Right now it's a bit difficult to do that which isn't super hacky.
It sounds like we need to fix or replace Jest before we can land this in RTL 😕
Well not necessarily. Depends on what strategy you want. E.g. you can support async function in client components as an approximation. There can also be a different mode that only executes the Server Components and not the client component shallowly. It's just that the ideal solution would ideally use two graphs.
Alternatively, couldn't the server renderer be spawned in a different environment by Testing Library (potentially using RPC) so we can keep the test assertions running in a client environment? I don't think it really makes sense to test a server's rendering without a client, considering there doesn't seem to be any meta framework that actually supports this yet, Testing Library's APIs are designed to work in browsers, and we want to test user interactions rather than internal framework implementation details.
Yea, if it can spawn a new process and it's enough to reuse the built-in Node.js module resolution it could be doable. Might miss out on some jest features like file watching, mocking etc that way but maybe it's enough.
It is a real shame that it appears testing is an afterthought when it comes to server components :(
The general strategy we recommend for React is E2E with Playwright or Cypress for a number of reasons. So that’s the thought. I know not everyone agrees with that testing strategy and want to try other thing and you’re free to.
Thanks @sebmarkbage . That is a strategy I've been considering myself recently. Are you doing component testing this way as well?
Do you have a mocking strategy at all that would help you test out different scenarios based on different data returned in component tests in this way?
Sorry I said a mocking strategy based on component tests but I meant for testing server components in general including how you'd test pages?
@citypaul Let's keep this discussion focused on React Testing Library please, there are better places to discuss React Server Components and testing in general. If you want to mock a network resource, we'd recommend using Mock Service Worker (example).
@citypaul Let's keep this discussion focused on React Testing Library please, there are better places to discuss React Server Components and testing in general. If you want to mock a network resource, we'd recommend using Mock Service Worker (example).
Sure, apologies for de-railing! :)
The moment I use async
on the server component and I do an await
inside the RSC I get
Jest encountered an unexpected token
Test suite failed to run
Jest encountered an unexpected token
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.
Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.
By default "node_modules" folder is ignored by transformers.
Here's what you can do:
• If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
• If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
• To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
• If you need a custom transformation specify a "transform" option in your config.
• If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.
You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation
Details:
[/Users/user/Apps/rap-portal-fe/node_modules/.pnpm/jose@4.14.4/node_modules/jose/dist/browser/index.js:1](mailto:/Users/user/Apps/rap-portal-fe/node_modules/.pnpm/jose@4.14.4/node_modules/jose/dist/browser/index.js:1)
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export { compactDecrypt } from './jwe/compact/decrypt.js';
^^^^^^
SyntaxError: Unexpected token 'export'
11 | <div className='nhsuk-width-container'>
12 | <h1>Hello</h1>
> 13 | </div>
| ^
14 | )
15 | }
16 |
at Runtime.createScriptFromCode ([../../node_modules/.pnpm/jest-runtime@29.5.0/node_modules/jest-runtime/build/index.js:1495:14](mailto:../../node_modules/.pnpm/jest-runtime@29.5.0/node_modules/jest-runtime/build/index.js:1495:14))
at Object.<anonymous> ([../../node_modules/.pnpm/openid-client@5.4.2/node_modules/openid-client/lib/client.js:8:14](mailto:../../node_modules/.pnpm/openid-client@5.4.2/node_modules/openid-client/lib/client.js:8:14))
at Object.<anonymous> ([../../node_modules/.pnpm/openid-client@5.4.2/node_modules/openid-client/lib/issuer.js:5:19](mailto:../../node_modules/.pnpm/openid-client@5.4.2/node_modules/openid-client/lib/issuer.js:5:19))
at Object.<anonymous> ([../../node_modules/.pnpm/openid-client@5.4.2/node_modules/openid-client/lib/index.js:1:36](mailto:../../node_modules/.pnpm/openid-client@5.4.2/node_modules/openid-client/lib/index.js:1:36))
at Object.<anonymous> ([../../node_modules/.pnpm/next-auth@4.22.1_next@13.4.3_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/core/lib/oauth/callback.js:8:21](mailto:../../node_modules/.pnpm/next-auth@4.22.1_next@13.4.3_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/core/lib/oauth/callback.js:8:21))
at Object.<anonymous> ([../../node_modules/.pnpm/next-auth@4.22.1_next@13.4.3_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/core/routes/callback.js:10:40](mailto:../../node_modules/.pnpm/next-auth@4.22.1_next@13.4.3_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/core/routes/callback.js:10:40))
at Object.<anonymous> ([../../node_modules/.pnpm/next-auth@4.22.1_next@13.4.3_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/core/routes/index.js:39:40](mailto:../../node_modules/.pnpm/next-auth@4.22.1_next@13.4.3_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/core/routes/index.js:39:40))
at Object.<anonymous> ([../../node_modules/.pnpm/next-auth@4.22.1_next@13.4.3_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/core/index.js:14:38](mailto:../../node_modules/.pnpm/next-auth@4.22.1_next@13.4.3_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/core/index.js:14:38))
at Object.<anonymous> ([../../node_modules/.pnpm/next-auth@4.22.1_next@13.4.3_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/next/index.js:10:13](mailto:../../node_modules/.pnpm/next-auth@4.22.1_next@13.4.3_react-dom@18.2.0_react@18.2.0/node_modules/next-auth/next/index.js:10:13))
at Object.<anonymous> (src/app/page.tsx:13:15)
at Object.<anonymous> (__tests__/pages/Home.test.tsx:16:54)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.492 s, estimated 1 s
Ran all test suites related to changed files.
I've been troubleshooting this the whole day
Describe the feature you'd like:
As a user of react 18 with NextJS (with app directory), I would like to render async server components
example: // Page.tsx
... // Page.test.tsx
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.
Current progress, workarounds, and demo