diff --git a/.changeset/router-testing-utilities.md b/.changeset/router-testing-utilities.md new file mode 100644 index 0000000000..4c5b585532 --- /dev/null +++ b/.changeset/router-testing-utilities.md @@ -0,0 +1,14 @@ +--- +'@tanstack/router-core': minor +'@tanstack/react-router': minor +'@tanstack/solid-router': minor +'@tanstack/vue-router': minor +--- + +Add experimental, typed test utilities for routes, exported from `@tanstack/react-router/testing`, `@tanstack/solid-router/testing` and `@tanstack/vue-router/testing`. Both return a router to render with `RouterProvider`. + +`createTestRouter` takes the options of `createRouter`, plus `location` and `overrides`, and creates a router over a copy of the app's route tree. Every route runs the app's own lifecycle unless an override for its id replaces `beforeLoad`, `loader`, `context` or a component option, or seeds its `loaderData` or `routeContext`. + +`createIsolatedTestRouter` renders one element inside one route with the params, search, context and loader data the test supplies. No `context`, `beforeLoad` or `loader` runs and no route component renders. Everything a test passes is typed from the route tree, so the state a route promises to its components is required by the types. + +The implementation lives in `@tanstack/router-core/testing`; the framework packages are thin typed wrappers around it. diff --git a/docs/router/api/router.md b/docs/router/api/router.md index 2c5ede186c..f50ebad032 100644 --- a/docs/router/api/router.md +++ b/docs/router/api/router.md @@ -12,6 +12,8 @@ title: Router API - [`createLazyRoute`](./router/createLazyRouteFunction.md) - [`createRouteMask`](./router/createRouteMaskFunction.md) - [`createRouter`](./router/createRouterFunction.md) + - [`createTestRouter`](./router/createTestRouterFunction.md) (experimental) + - [`createIsolatedTestRouter`](./router/createIsolatedTestRouterFunction.md) (experimental) - [`defer`](./router/deferFunction.md) - [`getRouteApi`](./router/getRouteApiFunction.md) - [`isNotFound`](./router/isNotFoundFunction.md) diff --git a/docs/router/api/router/createIsolatedTestRouterFunction.md b/docs/router/api/router/createIsolatedTestRouterFunction.md new file mode 100644 index 0000000000..a3b9ab32cc --- /dev/null +++ b/docs/router/api/router/createIsolatedTestRouterFunction.md @@ -0,0 +1,92 @@ +--- +id: createIsolatedTestRouterFunction +title: createIsolatedTestRouter function +--- + +> **Experimental:** `createIsolatedTestRouter` is experimental and subject to change. It is available for React, Solid and Vue. + +The `createIsolatedTestRouter` function creates a [`Router`](./RouterType.md) that renders one element inside one route of the app's route tree, with the state the test supplies. Import it from the `testing` subpath of your framework package: `@tanstack/react-router/testing`, `@tanstack/solid-router/testing` or `@tanstack/vue-router/testing`. The [Testing Routes guide](../../guide/testing-routes.md) shows how to use it. + +No `context`, `beforeLoad` or `loader` option of any route runs, no route component renders, and lazy routes are not loaded. The options that derive state from the URL (`params.parse`, `validateSearch`, the `search` middlewares and `loaderDeps`) run as in the app. + +## createIsolatedTestRouter options + +The `createIsolatedTestRouter` function accepts the following properties, plus the [`RouterOptions`](./RouterOptionsType.md) that [`createRouter`](./createRouterFunction.md) accepts, except `history`, `context`, `search` and the deprecated `notFoundRoute`, which test routers do not support. It leaves out `defaultComponent`, `defaultPendingComponent`, `defaultErrorComponent` and `defaultNotFoundComponent`, and sets `disableGlobalCatchBoundary`. + +### `routeTree` property + +- Type: `AnyRoute` +- Required +- The route tree of the app. The other options are typed from it. + +### `route` property + +- Type: a route id of the route tree +- Required +- The route the element renders in. For the root route, pass the exported `rootRouteId`. + +### `element` property + +- Type: React: `React.ReactElement`. Solid: `() => JSX.Element`, because Solid evaluates JSX right away. Vue: `VNode`. +- Required +- The element under test. It renders in place of the route's component. + +### `params` property + +- Type: the path params of the route +- Required when the route has path params + +### `search` property + +- Type: the search params a link to the route takes +- Required when the route requires search params +- They go through the route's `validateSearch`. + +### `context` property + +- Type: the whole context of the route, as `useRouteContext` returns it +- Required when the context has values + +### `loaderData` property + +- Type: loader data by route id, for the route and the routes above it +- Required when one of these routes has a loader that returns data. Each such route needs an entry; the root route's key is `[rootRouteId]`. + +## createIsolatedTestRouter returns + +- A promise of a [`Router`](./RouterType.md) typed with the route tree. It resolves once the router has loaded, so the first render of `` is complete. + +The promise rejects when `route` does not exist, when a path param is missing, when a route on the way to `route` fails to load (for example because its `validateSearch` rejects the search params, or its `params.parse` or `validateSearch` throws `notFound()`), and when the location of `route` does not lead to it, as for a pathless layout route. + +## Types + +`@tanstack/react-router/testing` also exports these types: + +- `IsolatedRouteState`: `route`, `params`, `search`, `context` and `loaderData` for one route. +- `CreateIsolatedTestRouterOptions`: the options of `createIsolatedTestRouter`. + +For the framework-independent parts, see [`createTestRouter`](./createTestRouterFunction.md#framework-independent-core). + +## Examples + +```tsx +import { render, screen } from '@testing-library/react' +import { RouterProvider } from '@tanstack/react-router' +import { createIsolatedTestRouter } from '@tanstack/react-router/testing' +import { routeTree } from './routeTree.gen' + +const router = await createIsolatedTestRouter({ + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: '1' }, + context: { locale: 'en', session: { user: ada }, user: ada }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post }, + }, +}) +render() + +screen.getByRole('heading', { name: post.title }) +``` diff --git a/docs/router/api/router/createTestRouterFunction.md b/docs/router/api/router/createTestRouterFunction.md new file mode 100644 index 0000000000..ba578e1f89 --- /dev/null +++ b/docs/router/api/router/createTestRouterFunction.md @@ -0,0 +1,104 @@ +--- +id: createTestRouterFunction +title: createTestRouter function +--- + +> **Experimental:** `createTestRouter` is experimental and subject to change. It is available for React, Solid and Vue. + +The `createTestRouter` function creates a [`Router`](./RouterType.md) for a test, over a copy of the app's route tree, and lets the test replace parts of single routes. Import it from the `testing` subpath of your framework package: `@tanstack/react-router/testing`, `@tanstack/solid-router/testing` or `@tanstack/vue-router/testing`. The [Testing Routes guide](../../guide/testing-routes.md) shows how to use it. + +## createTestRouter options + +The `createTestRouter` function accepts the [`RouterOptions`](./RouterOptionsType.md) that [`createRouter`](./createRouterFunction.md) accepts, plus the following properties. It does not support the deprecated `notFoundRoute` option: give the root route a `notFoundComponent` instead. + +### `routeTree` property + +- Type: `AnyRoute` +- Required +- The route tree of the app. The test router is built from a copy of it, and the other options are typed from it. + +### `location` property + +- Type: [`NavigateOptions`](./NavigateOptionsType.md), checked against the route tree +- Optional +- Where the router starts. It replaces the current entry of the router's history. Without it, the router starts at the current location of its history: `/` for the default memory history. + +### `overrides` property + +- Type: `RouteTestOverrides` +- Optional +- [Route overrides](#route-overrides) by route id. A route that is not listed keeps the app's options. + +### `history` property + +- Type: `RouterHistory` +- Optional +- Defaults to a memory history, not to the browser history that `createRouter` uses. + +## Route overrides + +An override for one route id. Every property is typed from that route. The root route's id is the exported `rootRouteId`, used as a computed key: `{ [rootRouteId]: { ... } }`. + +| Property | Type | Effect | +| ---------------------------------------------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------- | +| `beforeLoad` | The route's `beforeLoad` function type | Replaces the route's `beforeLoad`. | +| `loader` | A function that returns the route's loader data | Replaces the route's loader. | +| `context` | The route's `context` function type | Replaces the route's `context` option. | +| `loaderData` | The route's loader data | A seed: the loader is replaced by one that returns it. | +| `routeContext` | What the route's `context` and `beforeLoad` add to the context | A seed: neither the route's `context` option nor its `beforeLoad` runs. | +| `component`, `pendingComponent`, `errorComponent`, `notFoundComponent` | The route's component option types | Replace what the route renders. | + +Setting a property to `undefined` removes that option from the route. + +## createTestRouter returns + +- A [`Router`](./RouterType.md) typed with the route tree. It has not loaded yet: render it with `RouterProvider`, or call `router.load()`. + +It throws when `overrides` names a route that does not exist, gives a route both `loader` and `loaderData`, gives a route `routeContext` together with `context` or `beforeLoad`, or passes a value instead of a function as `context`. + +## Types + +`@tanstack/react-router/testing` also exports these types: + +- `RouteTestOverrides`: overrides by route id, for example to check a shared override object with `satisfies`. +- `CreateTestRouterOptions`: the options of `createTestRouter`. +- `RouteTestBeforeLoadFn`, `RouteTestLoaderFn` and `RouteTestContextFn`: the replacement functions for one route. + +## Framework-independent core + +`@tanstack/router-core/testing` holds the parts that do not depend on a framework. The React, Solid and Vue packages are thin typed wrappers around it; apps use those. + +| Export | What it does | +| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `createTestRouterWith(createRouter, options)` | `createTestRouter`, given a framework's `createRouter`. | +| `createIsolatedTestRouterWith(createRouter, options)` | `createIsolatedTestRouter`, given a framework's `createRouter`. It takes the route `component` that renders the element under test instead of `element`. | +| `TestRouterOptions`, `IsolatedTestRouterOptions` | The option types, with type parameters for a framework's component and element types. | +| `createTestRouteTree(routeTree, overrides)` | Copies a route tree and applies the overrides. | +| `createIsolatedRouteTree(routeTree, { routeId, component, loaderData })` | Copies a route tree without any option that does work or renders. The route `routeId` renders `component`, and the routes in the `loaderData` map return their data. | +| `initRouteTree(routeTree)` | Gives every route of a tree that no router has processed its `id`, `path`, `fullPath` and `to`. | +| `setTestRouterLocation(router, location)` | Moves a router that has not loaded to a location given as navigation options. | +| `assertRouteTestParams(router, routeId, params)` | Throws when a path param of the route is missing. | +| `assertIsolatedRouteLoaded(router, routeId)` | Throws the error of a match that failed, or an error when the route is not matched. | + +## Examples + +```tsx +import { render, screen } from '@testing-library/react' +import { RouterProvider, rootRouteId } from '@tanstack/react-router' +import { createTestRouter } from '@tanstack/react-router/testing' +import { routeTree } from './routeTree.gen' + +const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: '1' } }, + overrides: { + // Seeds: neither the root route's beforeLoad nor the post loader runs. + [rootRouteId]: { routeContext: { session: { user: ada } } }, + '/_authed/posts/$postId': { loaderData: { post } }, + }, +}) +render() + +await screen.findByRole('heading', { name: post.title }) +``` diff --git a/docs/router/config.json b/docs/router/config.json index 1258ddd817..f846f3f514 100644 --- a/docs/router/config.json +++ b/docs/router/config.json @@ -300,11 +300,21 @@ "frameworks": [ { "label": "react", - "children": [] + "children": [ + { + "label": "Testing Routes", + "to": "guide/testing-routes" + } + ] }, { "label": "solid", - "children": [] + "children": [ + { + "label": "Testing Routes", + "to": "guide/testing-routes" + } + ] } ] }, diff --git a/docs/router/guide/testing-routes.md b/docs/router/guide/testing-routes.md new file mode 100644 index 0000000000..ec3d608b7b --- /dev/null +++ b/docs/router/guide/testing-routes.md @@ -0,0 +1,312 @@ +--- +id: testing-routes +title: Testing Routes +--- + +> **Experimental:** The route testing utilities are experimental and subject to change. They are available for React, Solid and Vue. + +The `testing` subpath of each framework package (`@tanstack/react-router/testing`, `@tanstack/solid-router/testing`, `@tanstack/vue-router/testing`) creates routers for tests from your app's route tree. The examples on this page use React; [Solid and Vue](#solid-and-vue) lists what differs. + +Tests address routes by their id, and everything a test passes is typed from the tree: the start location, params, search params, context, loader data, and the parts of a route it replaces. Tests never declare routes of their own. + +Each has the same two functions. Both return a router that you render with `RouterProvider`, so they work with any test library: + +| Function | Use it to test | What runs | +| -------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------- | +| `createTestRouter` | A route or a flow: redirects, loaders, layouts, errors, navigation | Your routes' `context`, `beforeLoad` and `loader`, unless the test replaces them | +| `createIsolatedTestRouter` | A component that reads route state: params, search, context, loader data | None of them. The test supplies the state the component reads, and the TypeScript types require all of it | + +## Setup + +Both functions take your route tree. With file-based routing, import the generated `routeTree.gen.ts`, and keep the router plugin in the Vite config your tests use, so the file is regenerated when a test run starts: + +```ts title="vite.config.ts" +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ target: 'react', autoCodeSplitting: true }), + react(), + ], + test: { + environment: 'jsdom', + // Type-check the tests, so that a test that leaves out route state fails. + typecheck: { enabled: true }, + }, +}) +``` + +For Solid or Vue, pass `target: 'solid'` or `target: 'vue'`, and use your framework's Vite plugin. With code-based routing, pass the route tree you build with `addChildren`. + +## The example app + +The examples on this page use this app, which also has a `/login` route: + +```tsx title="src/routes/__root.tsx" +export const Route = createRootRouteWithContext<{ locale: string }>()({ + beforeLoad: async () => ({ session: await fetchSession() }), + component: RootLayout, +}) +``` + +```tsx title="src/routes/_authed.tsx" +export const Route = createFileRoute('/_authed')({ + beforeLoad: ({ context }) => { + if (!context.session.user) { + throw redirect({ to: '/login' }) + } + return { user: context.session.user } + }, + loader: async () => ({ unreadCount: await fetchUnreadCount() }), + component: AuthedLayout, +}) +``` + +```tsx title="src/routes/_authed/posts.$postId.tsx" +export const Route = createFileRoute('/_authed/posts/$postId')({ + loader: async ({ params }) => ({ post: await fetchPost(params.postId) }), + component: PostPage, +}) +``` + +```tsx title="src/components/PostHeader.tsx" +const postRoute = getRouteApi('/_authed/posts/$postId') + +export function PostHeader() { + const { post } = postRoute.useLoaderData() + const { user } = postRoute.useRouteContext() + + return ( +
+

{post.title}

+ {post.authorId === user.id ? Written by you : null} +
+ ) +} +``` + +## Test a route with `createTestRouter` + +`createTestRouter` takes the options of `createRouter`, plus `location` and `overrides`. It creates a router over a copy of your route tree, and every route behaves as in the app unless the test replaces part of it: + +```tsx title="tests/post-route.test.tsx" +import { render, screen } from '@testing-library/react' +import { RouterProvider, rootRouteId } from '@tanstack/react-router' +import { createTestRouter } from '@tanstack/react-router/testing' +import { expect, test } from 'vitest' +import { routeTree } from '../src/routeTree.gen' + +test('sends a signed-out visitor to the login page', async () => { + const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: '1' } }, + overrides: { + // The root route's beforeLoad does not run. This is its result. + [rootRouteId]: { routeContext: { session: { user: null } } }, + }, + }) + render() + + expect(await screen.findByRole('heading', { name: 'Sign in' })).toBeTruthy() + expect(router.state.location.pathname).toBe('/login') +}) +``` + +The test does not replace the `beforeLoad` of `/_authed`, so it runs, finds no user and redirects. + +- `location` is typed like the options of `navigate`: `to` must be a path of your app, and the path params and search params that path requires are required here too. It replaces the current entry of the router's history. Without it, the router starts at the current location of its history: `/` for the default memory history. +- The router uses a memory history, unless you pass your own `history`. +- `context` and every other option go to the router as in `createRouter`. +- The router has not loaded yet. Render it with `RouterProvider`, or `await router.load()` to assert on `router.state` without rendering anything. +- Every call builds a new copy of the route tree. Overrides never reach another test, and the route objects your app imports keep their options. + +### Replace parts of a route + +`overrides` takes overrides by route id. For the root route, use the `rootRouteId` that `@tanstack/react-router` exports, as a computed key: `[rootRouteId]`. Each override is typed from the route it replaces: + +| Override | Effect | +| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `beforeLoad`, `loader`, `context` | Replace the route option of the same name. Each takes a function that receives what the original receives and has to return what the original returns. | +| `loaderData` | A seed: the route's loader is replaced by one that returns this value. | +| `routeContext` | A seed: everything the route adds to the context. Neither the route's `context` option nor its `beforeLoad` runs. | +| `component`, `pendingComponent`, `errorComponent`, `notFoundComponent` | Replace what the route renders. An override also wins over the options of a [lazy route](./code-splitting.md) once they have loaded. | + +Setting an option to `undefined` removes it. A route cannot take both `loader` and `loaderData`, or `routeContext` together with `context` or `beforeLoad`. The options that derive state from the URL cannot be replaced, because replacing them would change the route's types: `params.parse` and `params.stringify`, `validateSearch`, the `search` middlewares and `loaderDeps` run as in the app. + +```tsx +const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: '7' } }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: ada } } }, + '/_authed': { loaderData: { unreadCount: 3 } }, + '/_authed/posts/$postId': { + loader: ({ params }) => ({ post: createPost({ id: params.postId }) }), + }, + }, +}) +``` + +Here the real `beforeLoad` of `/_authed` derives `user` from the seeded session. A loader that returns the wrong data, or an override for a route id that does not exist, is a type error. + +To reuse overrides in several tests, check them against `RouteTestOverrides` and spread them: + +```tsx title="tests/fixtures.ts" +import { rootRouteId } from '@tanstack/react-router' +import type { RouteTestOverrides } from '@tanstack/react-router/testing' +import type { routeTree } from '../src/routeTree.gen' + +export const signedIn = { + [rootRouteId]: { routeContext: { session: { user: ada } } }, +} satisfies RouteTestOverrides +``` + +```tsx +overrides: { ...signedIn, '/_authed': { loaderData: { unreadCount: 3 } } }, +``` + +## Test a component with `createIsolatedTestRouter` + +`createIsolatedTestRouter` creates a router that renders one element inside one route. The test supplies the state the route would have in the app: + +```tsx title="tests/post-header.test.tsx" +import { render, screen } from '@testing-library/react' +import { RouterProvider } from '@tanstack/react-router' +import { createIsolatedTestRouter } from '@tanstack/react-router/testing' +import { expect, test } from 'vitest' +import { PostHeader } from '../src/components/PostHeader' +import { routeTree } from '../src/routeTree.gen' + +test('marks posts written by the signed-in user', async () => { + const router = await createIsolatedTestRouter({ + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: '1' }, + context: { locale: 'en', session: { user: ada }, user: ada }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost({ authorId: ada.id }) }, + }, + }) + render() + + expect(screen.getByText('Written by you')).toBeTruthy() +}) +``` + +`element` renders in place of the route's component. No `context`, `beforeLoad` or `loader` option of any route runs, none of your route components render, and lazy routes are not loaded, so nothing of the app runs around the element. The function resolves once the router has loaded, so the first render is complete. + +The router is real: links get their real `href`, and navigation updates `router.state`, but every route other than the one under test renders nothing. + +### What the types require + +The options are typed from the route that `route` names. They ask for what the skipped options would have produced: + +| Option | Contains | Required when | +| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------- | +| `params` | All path params of the route | The route has path params | +| `search` | The search params, as a link to the route takes them. They go through the route's `validateSearch`. | The route requires search params | +| `context` | The route's whole context: the router context and everything each route above it adds. It is what `useRouteContext` returns for the route. | The context has values | +| `loaderData` | Loader data by route id, for the route and the routes above it | One of these routes has a loader that returns data. It needs an entry. | + +In the example, `context` has to hold `locale` from the router context, `session` from the root route and `user` from `/_authed`, and `loaderData` has to hold the data of `/_authed` and of the post route. Leaving any of them out is a type error that names the missing value. For the root route, use `route: rootRouteId`, and `[rootRouteId]` as its key in `loaderData`. + +> [!NOTE] +> Vitest checks these types only when [type checking](https://vitest.dev/guide/testing-types) is on: set `test.typecheck.enabled` as in the [setup](#setup), or run `vitest --typecheck`. Vitest then runs `tsc` with your `tsconfig.json`, and a type error in a test file that the tsconfig includes fails the run, with its file and line. By default Vitest lists such an error as a source error; add your test files to `typecheck.include` to have it reported as a failure of the test that contains it. Without type checking, Vitest only strips the types: a test that leaves state out still runs, and the component reads `undefined`. + +At run time, `createIsolatedTestRouter` rejects with a message when: + +- `route` is not a route of the tree, +- a path param is missing, +- a route on the way to `route` fails to load, for example because its `validateSearch` rejects the search params, or its `params.parse` or `validateSearch` throws `notFound()`, +- the location of the route does not lead to it. A pathless layout route has no location of its own: render the element in one of its child routes, and read the layout's state with `getRouteApi('/_layout')`. + +## Share state across tests + +There is no configuration step. Share state the way you share any test data, and spread it into each call; the types check the object that a test ends up passing: + +```tsx title="tests/fixtures.ts" +export const signedInContext = { + locale: 'en', + session: { user: ada }, + user: ada, +} +``` + +```tsx +const router = await createIsolatedTestRouter({ + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: '1' }, + context: { ...signedInContext, user: grace }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, +}) +``` + +## Router options + +Both functions pass their other options to the router, for example `Wrap` for the providers your components need: + +```tsx +const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + Wrap: ({ children }) => ( + {children} + ), +}) +``` + +Neither function supports the deprecated `notFoundRoute` option: give the root route a `notFoundComponent` instead. + +`createIsolatedTestRouter` leaves out `defaultComponent`, `defaultPendingComponent`, `defaultErrorComponent` and `defaultNotFoundComponent`, and turns off the router's global error boundary, so the router does not catch an error that the element throws. It creates its own history and sets its location from `route`, `params` and `search`; its `search` is the route's search params, not the router option of that name. + +## Solid and Vue + +`@tanstack/solid-router/testing` and `@tanstack/vue-router/testing` have the same two functions with the same options. Only the element under test and the call that renders the router differ: + +| Framework | `element` | Render the router | +| --------- | -------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| React | `` | `render()` from `@testing-library/react` | +| Solid | `() => `, because Solid evaluates JSX right away | `render(() => )` from `@solidjs/testing-library` | +| Vue | A vnode: `` with Vue JSX, or `h(PostHeader)` | `render()` from `@testing-library/vue` | + +```tsx title="tests/post-header.test.tsx (Solid)" +import { render, screen } from '@solidjs/testing-library' +import { RouterProvider } from '@tanstack/solid-router' +import { createIsolatedTestRouter } from '@tanstack/solid-router/testing' + +const router = await createIsolatedTestRouter({ + routeTree, + route: '/_authed/posts/$postId', + element: () => , + params: { postId: '1' }, + context: { locale: 'en', session: { user: ada }, user: ada }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost({ authorId: ada.id }) }, + }, +}) +render(() => ) +``` + +In Vue, `Wrap` is a component that renders its default slot. + +## Limitations + +- Every test router loads your whole route tree, so every route module is imported, with its top-level code and its imports. +- The utilities are tested with Vitest in jsdom only. +- TanStack Start apps are not supported yet. Importing the route tree in a test also imports the server-only code of your route files. + +## API + +See the [`createTestRouter`](../api/router/createTestRouterFunction.md) and [`createIsolatedTestRouter`](../api/router/createIsolatedTestRouterFunction.md) references. diff --git a/docs/router/how-to/setup-testing.md b/docs/router/how-to/setup-testing.md index 104cbedc0d..a35c3bff69 100644 --- a/docs/router/how-to/setup-testing.md +++ b/docs/router/how-to/setup-testing.md @@ -8,6 +8,8 @@ Set up testing by configuring your test framework (Vitest/Jest), creating router > **Using File-Based Routing?** See [How to Test File-Based Routing](./test-file-based-routing.md) for patterns specific to file-based routing applications. +> **Typed test routers:** `@tanstack/react-router/testing` creates test routers from your app's route tree and types every override from it, so tests do not declare routes of their own. It is experimental; see [Testing Routes](../guide/testing-routes.md). + --- ## Configure Test Framework diff --git a/docs/router/how-to/test-file-based-routing.md b/docs/router/how-to/test-file-based-routing.md index aa679719b5..c74b31b11d 100644 --- a/docs/router/how-to/test-file-based-routing.md +++ b/docs/router/how-to/test-file-based-routing.md @@ -8,6 +8,8 @@ This guide covers testing TanStack Router applications that use file-based routi Test file-based routing by setting up route mocking utilities, testing generated route trees, and implementing patterns specific to file-based route structures and conventions. +> **Typed test routers:** `@tanstack/react-router/testing` creates test routers from your generated route tree and types every override from it, so tests do not declare routes of their own. It is experimental; see [Testing Routes](../guide/testing-routes.md). + --- ## Understanding File-Based Routing Testing diff --git a/e2e/react-router/route-testing/.gitignore b/e2e/react-router/route-testing/.gitignore new file mode 100644 index 0000000000..2c5b3c96f1 --- /dev/null +++ b/e2e/react-router/route-testing/.gitignore @@ -0,0 +1,4 @@ +node_modules +.DS_Store +dist +*.local diff --git a/e2e/react-router/route-testing/package.json b/e2e/react-router/route-testing/package.json new file mode 100644 index 0000000000..7d16bbf02e --- /dev/null +++ b/e2e/react-router/route-testing/package.json @@ -0,0 +1,23 @@ +{ + "name": "tanstack-router-e2e-react-route-testing", + "private": true, + "type": "module", + "scripts": { + "test:e2e": "vitest run" + }, + "dependencies": { + "@tanstack/react-router": "workspace:^", + "@tanstack/router-plugin": "workspace:^", + "react": "catalog:", + "react-dom": "catalog:" + }, + "devDependencies": { + "@testing-library/react": "catalog:", + "@types/react": "catalog:", + "@types/react-dom": "catalog:", + "@vitejs/plugin-react": "catalog:", + "jsdom": "catalog:", + "vite": "catalog:", + "vitest": "catalog:" + } +} diff --git a/e2e/react-router/route-testing/src/api.ts b/e2e/react-router/route-testing/src/api.ts new file mode 100644 index 0000000000..1d41b0c3e1 --- /dev/null +++ b/e2e/react-router/route-testing/src/api.ts @@ -0,0 +1,35 @@ +export interface User { + id: string + name: string +} + +export interface Session { + user: User | null +} + +export interface Post { + id: string + title: string + authorId: string + status: 'draft' | 'published' +} + +async function getJson(url: string): Promise { + const response = await fetch(url) + if (!response.ok) { + throw new Error(`Request to ${url} failed with status ${response.status}`) + } + return response.json() as Promise +} + +export function fetchSession() { + return getJson('/api/session') +} + +export function fetchUnreadCount() { + return getJson('/api/notifications/unread-count') +} + +export function fetchPost(postId: string) { + return getJson(`/api/posts/${postId}`) +} diff --git a/e2e/react-router/route-testing/src/components/PostHeader.tsx b/e2e/react-router/route-testing/src/components/PostHeader.tsx new file mode 100644 index 0000000000..f6f03b5542 --- /dev/null +++ b/e2e/react-router/route-testing/src/components/PostHeader.tsx @@ -0,0 +1,25 @@ +import { Link, getRouteApi } from '@tanstack/react-router' + +const postRoute = getRouteApi('/_authed/posts/$postId') + +export function PostHeader() { + const { post } = postRoute.useLoaderData() + const { user } = postRoute.useRouteContext() + const { tab } = postRoute.useSearch() + const { postId } = postRoute.useParams() + + return ( +
+

{post.title}

+ {post.status === 'draft' ? Draft : null} + {post.authorId === user.id ? Written by you : null} + + {tab === 'details' ? 'Show comments' : 'Show details'} + +
+ ) +} diff --git a/e2e/react-router/route-testing/src/components/UserMenu.tsx b/e2e/react-router/route-testing/src/components/UserMenu.tsx new file mode 100644 index 0000000000..6f10393283 --- /dev/null +++ b/e2e/react-router/route-testing/src/components/UserMenu.tsx @@ -0,0 +1,16 @@ +import { Link, getRouteApi } from '@tanstack/react-router' + +const authedRoute = getRouteApi('/_authed') + +export function UserMenu() { + const { user } = authedRoute.useRouteContext() + const { unreadCount } = authedRoute.useLoaderData() + + return ( +
+ {user.name} + {unreadCount} unread + Sign out +
+ ) +} diff --git a/e2e/react-router/route-testing/src/routeTree.gen.ts b/e2e/react-router/route-testing/src/routeTree.gen.ts new file mode 100644 index 0000000000..c5f07c792c --- /dev/null +++ b/e2e/react-router/route-testing/src/routeTree.gen.ts @@ -0,0 +1,119 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ + id: '/posts/$postId', + path: '/posts/$postId', + getParentRoute: () => AuthedRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/login': typeof LoginRoute + '/posts/$postId': typeof AuthedPostsPostIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/login': typeof LoginRoute + '/posts/$postId': typeof AuthedPostsPostIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_authed': typeof AuthedRouteWithChildren + '/login': typeof LoginRoute + '/_authed/posts/$postId': typeof AuthedPostsPostIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/login' | '/posts/$postId' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/login' | '/posts/$postId' + id: '__root__' | '/' | '/_authed' | '/login' | '/_authed/posts/$postId' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AuthedRoute: typeof AuthedRouteWithChildren + LoginRoute: typeof LoginRoute +} + +declare module '@tanstack/react-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed/posts/$postId': { + id: '/_authed/posts/$postId' + path: '/posts/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof AuthedPostsPostIdRouteImport + parentRoute: typeof AuthedRoute + } + } +} + +interface AuthedRouteChildren { + AuthedPostsPostIdRoute: typeof AuthedPostsPostIdRoute +} + +const AuthedRouteChildren: AuthedRouteChildren = { + AuthedPostsPostIdRoute: AuthedPostsPostIdRoute, +} + +const AuthedRouteWithChildren = + AuthedRoute._addFileChildren(AuthedRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AuthedRoute: AuthedRouteWithChildren, + LoginRoute: LoginRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/e2e/react-router/route-testing/src/router.tsx b/e2e/react-router/route-testing/src/router.tsx new file mode 100644 index 0000000000..43f50d8f8a --- /dev/null +++ b/e2e/react-router/route-testing/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/react-router' +import { routeTree } from './routeTree.gen' + +export function createAppRouter() { + return createRouter({ + routeTree, + context: { locale: 'en' }, + defaultPreload: 'intent', + }) +} + +declare module '@tanstack/react-router' { + interface Register { + router: ReturnType + } +} diff --git a/e2e/react-router/route-testing/src/routes/__root.tsx b/e2e/react-router/route-testing/src/routes/__root.tsx new file mode 100644 index 0000000000..2e414563a4 --- /dev/null +++ b/e2e/react-router/route-testing/src/routes/__root.tsx @@ -0,0 +1,26 @@ +import { + Link, + Outlet, + createRootRouteWithContext, +} from '@tanstack/react-router' +import { fetchSession } from '../api' + +export interface RouterContext { + locale: string +} + +export const Route = createRootRouteWithContext()({ + beforeLoad: async () => ({ session: await fetchSession() }), + component: RootComponent, +}) + +function RootComponent() { + return ( + <> + + + + ) +} diff --git a/e2e/react-router/route-testing/src/routes/_authed.tsx b/e2e/react-router/route-testing/src/routes/_authed.tsx new file mode 100644 index 0000000000..27d948a500 --- /dev/null +++ b/e2e/react-router/route-testing/src/routes/_authed.tsx @@ -0,0 +1,23 @@ +import { Outlet, createFileRoute, redirect } from '@tanstack/react-router' +import { fetchUnreadCount } from '../api' +import { UserMenu } from '../components/UserMenu' + +export const Route = createFileRoute('/_authed')({ + beforeLoad: ({ context, location }) => { + if (!context.session.user) { + throw redirect({ to: '/login', search: { redirect: location.href } }) + } + return { user: context.session.user } + }, + loader: async () => ({ unreadCount: await fetchUnreadCount() }), + component: AuthedLayout, +}) + +function AuthedLayout() { + return ( + <> + + + + ) +} diff --git a/e2e/react-router/route-testing/src/routes/_authed/posts.$postId.tsx b/e2e/react-router/route-testing/src/routes/_authed/posts.$postId.tsx new file mode 100644 index 0000000000..97d4058a4f --- /dev/null +++ b/e2e/react-router/route-testing/src/routes/_authed/posts.$postId.tsx @@ -0,0 +1,35 @@ +import { createFileRoute } from '@tanstack/react-router' +import { fetchPost } from '../../api' +import { PostHeader } from '../../components/PostHeader' +import type { SearchSchemaInput } from '@tanstack/react-router' + +export type PostTab = 'details' | 'comments' + +export const Route = createFileRoute('/_authed/posts/$postId')({ + validateSearch: ( + search: { tab?: string } & SearchSchemaInput, + ): { tab: PostTab } => { + if (search.tab === undefined || search.tab === 'details') { + return { tab: 'details' } + } + if (search.tab === 'comments') { + return { tab: 'comments' } + } + throw new Error(`Unknown tab "${search.tab}"`) + }, + loader: async ({ params }) => ({ post: await fetchPost(params.postId) }), + component: PostPage, +}) + +function PostPage() { + const { tab } = Route.useSearch() + + return ( +
+ +
+ {tab === 'comments' ? 'Comments' : 'Details'} +
+
+ ) +} diff --git a/e2e/react-router/route-testing/src/routes/index.tsx b/e2e/react-router/route-testing/src/routes/index.tsx new file mode 100644 index 0000000000..db792756d1 --- /dev/null +++ b/e2e/react-router/route-testing/src/routes/index.tsx @@ -0,0 +1,16 @@ +import { Link, createFileRoute } from '@tanstack/react-router' + +export const Route = createFileRoute('/')({ + component: HomePage, +}) + +function HomePage() { + return ( +
+

Home

+ + First post + +
+ ) +} diff --git a/e2e/react-router/route-testing/src/routes/login.tsx b/e2e/react-router/route-testing/src/routes/login.tsx new file mode 100644 index 0000000000..80e99c8d87 --- /dev/null +++ b/e2e/react-router/route-testing/src/routes/login.tsx @@ -0,0 +1,21 @@ +import { createFileRoute } from '@tanstack/react-router' +import type { SearchSchemaInput } from '@tanstack/react-router' + +export const Route = createFileRoute('/login')({ + validateSearch: ( + search: { redirect?: string } & SearchSchemaInput, + ): { redirect?: string } => + typeof search.redirect === 'string' ? { redirect: search.redirect } : {}, + component: LoginPage, +}) + +function LoginPage() { + const { redirect } = Route.useSearch() + + return ( +
+

Sign in

+ {redirect ?

You will return to {redirect}

: null} +
+ ) +} diff --git a/e2e/react-router/route-testing/src/test-fixtures.ts b/e2e/react-router/route-testing/src/test-fixtures.ts new file mode 100644 index 0000000000..047a9f5d26 --- /dev/null +++ b/e2e/react-router/route-testing/src/test-fixtures.ts @@ -0,0 +1,20 @@ +import type { Post, User } from './api' + +export const testUser: User = { id: 'user-1', name: 'Ada' } + +export function createPost(overrides: Partial = {}): Post { + return { + id: 'post-1', + title: 'Hello world', + authorId: 'user-2', + status: 'published', + ...overrides, + } +} + +/** The context of the routes under `/_authed` for a signed-in test user. */ +export const signedInContext = { + locale: 'en', + session: { user: testUser }, + user: testUser, +} diff --git a/e2e/react-router/route-testing/tests/post-header.test.tsx b/e2e/react-router/route-testing/tests/post-header.test.tsx new file mode 100644 index 0000000000..27323f35ff --- /dev/null +++ b/e2e/react-router/route-testing/tests/post-header.test.tsx @@ -0,0 +1,118 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { RouterProvider } from '@tanstack/react-router' +import { createIsolatedTestRouter } from '@tanstack/react-router/testing' +import { describe, expect, test, vi } from 'vitest' +import { PostHeader } from '../src/components/PostHeader' +import { routeTree } from '../src/routeTree.gen' +import { createPost, signedInContext, testUser } from '../src/test-fixtures' + +const postRoute = { + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: 'post-1' }, + context: signedInContext, +} as const + +describe('a component rendered in its route with supplied state', () => { + test('reads loader data, context, search and params of the route', async () => { + const router = await createIsolatedTestRouter({ + ...postRoute, + loaderData: { + '/_authed': { unreadCount: 2 }, + '/_authed/posts/$postId': { + post: createPost({ title: 'Typed tests', authorId: testUser.id }), + }, + }, + }) + render() + + expect(screen.getByRole('heading').textContent).toBe('Typed tests') + expect(screen.getByText('Written by you')).toBeTruthy() + expect(screen.queryByText('Draft')).toBeNull() + + const link = screen.getByRole('link', { name: 'Show comments' }) + expect(link.getAttribute('href')).toBe('/posts/post-1?tab=comments') + }) + + test('runs no lifecycle of the application and renders none of its layout', async () => { + const fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) + + const router = await createIsolatedTestRouter({ + ...postRoute, + loaderData: { + '/_authed': { unreadCount: 2 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }) + render() + + expect(fetchMock).not.toHaveBeenCalled() + expect(screen.queryByRole('navigation')).toBeNull() + expect(screen.queryByLabelText('User menu')).toBeNull() + expect(screen.queryByLabelText('Tab content')).toBeNull() + }) + + test('shows the state the test supplies', async () => { + const router = await createIsolatedTestRouter({ + ...postRoute, + context: { ...signedInContext, user: { id: 'user-2', name: 'Grace' } }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost({ status: 'draft' }) }, + }, + }) + render() + + expect(screen.getByText('Draft')).toBeTruthy() + expect(screen.getByText('Written by you')).toBeTruthy() + }) + + test('sends search params through the validateSearch of the route', async () => { + const router = await createIsolatedTestRouter({ + ...postRoute, + search: { tab: 'comments' }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }) + render() + + expect(screen.getByRole('link', { name: 'Show details' })).toBeTruthy() + }) + + test('fails when the search params do not pass validateSearch', async () => { + await expect( + createIsolatedTestRouter({ + ...postRoute, + search: { tab: 'history' }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }), + ).rejects.toThrow('Unknown tab "history"') + }) + + test('navigates with the real router', async () => { + const router = await createIsolatedTestRouter({ + ...postRoute, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }) + render() + + fireEvent.click(screen.getByRole('link', { name: 'Show comments' })) + + await waitFor(() => { + expect(router.state.location.search).toEqual({ tab: 'comments' }) + }) + expect( + await screen.findByRole('link', { name: 'Show details' }), + ).toBeTruthy() + }) +}) diff --git a/e2e/react-router/route-testing/tests/post-route.test.tsx b/e2e/react-router/route-testing/tests/post-route.test.tsx new file mode 100644 index 0000000000..b16a1aa030 --- /dev/null +++ b/e2e/react-router/route-testing/tests/post-route.test.tsx @@ -0,0 +1,154 @@ +import { render, screen, waitFor } from '@testing-library/react' +import { RouterProvider, rootRouteId } from '@tanstack/react-router' +import { createTestRouter } from '@tanstack/react-router/testing' +import { describe, expect, test, vi } from 'vitest' +import { routeTree } from '../src/routeTree.gen' +import { createPost, testUser } from '../src/test-fixtures' +import type { Session } from '../src/api' + +function stubApi(responses: Record) { + const fetchMock = vi.fn((input: string | URL | Request) => { + const url = String(input) + return Promise.resolve( + url in responses + ? new Response(JSON.stringify(responses[url])) + : new Response('Not found', { status: 404 }), + ) + }) + vi.stubGlobal('fetch', fetchMock) + return fetchMock +} + +describe('a test router over the route tree of the application', () => { + test('runs the lifecycle of the application by default', async () => { + const fetchMock = stubApi({ + '/api/session': { user: testUser } satisfies Session, + '/api/notifications/unread-count': 3, + '/api/posts/post-1': createPost({ title: 'From the API' }), + }) + + const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + }) + render() + + expect( + await screen.findByRole('heading', { name: 'From the API' }), + ).toBeTruthy() + expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy() + expect(screen.getByLabelText('User menu').textContent).toContain('3 unread') + expect(screen.getByLabelText('Tab content').textContent).toBe('Details') + expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([ + '/api/session', + '/api/notifications/unread-count', + '/api/posts/post-1', + ]) + }) + + test('follows the redirect of a real beforeLoad', async () => { + stubApi({ '/api/session': { user: null } satisfies Session }) + + const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { + to: '/posts/$postId', + params: { postId: 'post-1' }, + search: { tab: 'comments' }, + }, + }) + render() + + expect(await screen.findByRole('heading', { name: 'Sign in' })).toBeTruthy() + expect(router.state.location.pathname).toBe('/login') + expect(router.state.location.search).toEqual({ + redirect: '/posts/post-1?tab=comments', + }) + }) + + test('replaces only the lifecycle options a test names', async () => { + const fetchMock = stubApi({}) + + const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-7' } }, + overrides: { + // A seed: the session lookup of the root route does not run. + [rootRouteId]: { routeContext: { session: { user: testUser } } }, + // A seed for the loader data. + '/_authed': { loaderData: { unreadCount: 5 } }, + // A replacement, typed like the loader of the route. + '/_authed/posts/$postId': { + loader: ({ params }) => ({ + post: createPost({ id: params.postId, title: 'From the test' }), + }), + }, + }, + }) + render() + + expect( + await screen.findByRole('heading', { name: 'From the test' }), + ).toBeTruthy() + // The beforeLoad of `/_authed` is not named, so the real one derived the + // user from the seeded session. + const menu = screen.getByLabelText('User menu') + expect(menu.textContent).toContain(testUser.name) + expect(menu.textContent).toContain('5 unread') + expect(fetchMock).not.toHaveBeenCalled() + }) + + test('replaces what a route renders', async () => { + stubApi({ + '/api/session': { user: testUser } satisfies Session, + '/api/notifications/unread-count': 0, + }) + + const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + overrides: { + '/_authed/posts/$postId': { + loaderData: { post: createPost() }, + component: () =>

Replaced page

, + }, + }, + }) + render() + + expect(await screen.findByText('Replaced page')).toBeTruthy() + expect(screen.queryByLabelText('Tab content')).toBeNull() + }) + + test('keeps overrides out of the next router', async () => { + const first = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: testUser } } }, + '/_authed': { loaderData: { unreadCount: 0 } }, + '/_authed/posts/$postId': { loaderData: { post: createPost() } }, + }, + }) + await first.load() + expect(first.state.matches.at(-1)?.status).toBe('success') + + const fetchMock = stubApi({ '/api/session': { user: null } }) + const second = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + }) + await second.load() + + await waitFor(() => { + expect(second.state.location.pathname).toBe('/login') + }) + expect(fetchMock).toHaveBeenCalledWith('/api/session') + }) +}) diff --git a/e2e/react-router/route-testing/tests/route-testing.test-d.tsx b/e2e/react-router/route-testing/tests/route-testing.test-d.tsx new file mode 100644 index 0000000000..7b3e16a321 --- /dev/null +++ b/e2e/react-router/route-testing/tests/route-testing.test-d.tsx @@ -0,0 +1,136 @@ +import { rootRouteId } from '@tanstack/react-router' +import { + createIsolatedTestRouter, + createTestRouter, +} from '@tanstack/react-router/testing' +import { describe, expectTypeOf, test } from 'vitest' +import { PostHeader } from '../src/components/PostHeader' +import { routeTree } from '../src/routeTree.gen' +import { createPost, signedInContext, testUser } from '../src/test-fixtures' +import type { Post, Session, User } from '../src/api' + +const postState = { + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: 'post-1' }, + context: signedInContext, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, +} as const + +describe('createIsolatedTestRouter is typed from the generated route tree', () => { + test('accepts the complete state of a route', () => { + void createIsolatedTestRouter(postState) + }) + + test('rejects a missing context value', () => { + const withoutUser = { + ...postState, + context: { locale: 'en', session: { user: testUser } }, + } as const + // @ts-expect-error `user` comes from the beforeLoad of `/_authed` and is missing + void createIsolatedTestRouter(withoutUser) + }) + + test('rejects missing loader data of the route and of its ancestors', () => { + const withoutRouteData = { + ...postState, + loaderData: { '/_authed': { unreadCount: 0 } }, + } as const + // @ts-expect-error the loader data of the route is missing + void createIsolatedTestRouter(withoutRouteData) + + const withoutAncestorData = { + ...postState, + loaderData: { '/_authed/posts/$postId': { post: createPost() } }, + } as const + // @ts-expect-error the loader data of `/_authed` is missing + void createIsolatedTestRouter(withoutAncestorData) + }) + + test('rejects loader data of the wrong shape', () => { + const wrongPost = { + ...postState, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { + post: { id: 'post-1', title: 'No status' }, + }, + }, + } as const + // @ts-expect-error `authorId` and `status` are missing from the post + void createIsolatedTestRouter(wrongPost) + }) + + test('rejects a route id that is not in the tree', () => { + const unknownRoute = { ...postState, route: '/posts/$postId' } as const + // @ts-expect-error the id of the route is `/_authed/posts/$postId` + void createIsolatedTestRouter(unknownRoute) + }) + + test('takes the root route by rootRouteId', () => { + void createIsolatedTestRouter({ + routeTree, + route: rootRouteId, + element: , + context: { locale: 'en', session: { user: testUser } }, + }) + }) +}) + +describe('createTestRouter is typed from the generated route tree', () => { + test('types a replacement like the option it replaces', () => { + createTestRouter({ + routeTree, + context: { locale: 'en' }, + overrides: { + [rootRouteId]: { + beforeLoad: ({ context }) => { + expectTypeOf(context).toEqualTypeOf<{ locale: string }>() + return { session: { user: testUser } } + }, + }, + '/_authed': { + beforeLoad: ({ context }) => { + expectTypeOf(context.session).toEqualTypeOf() + return { user: testUser } + }, + }, + '/_authed/posts/$postId': { + loader: ({ params, context }) => { + expectTypeOf(params).toEqualTypeOf<{ postId: string }>() + expectTypeOf(context.user).toEqualTypeOf() + return { post: createPost({ id: params.postId }) } + }, + }, + }, + }) + }) + + test('rejects a replacement that returns the wrong data', () => { + const wrongLoader = { + routeTree, + context: { locale: 'en' }, + overrides: { + '/_authed/posts/$postId': { + loader: (): { post: Pick } => ({ post: { id: '1' } }), + }, + }, + } + // @ts-expect-error the loader has to return a whole post + createTestRouter(wrongLoader) + }) + + test('types the start location like a link', () => { + const withoutParams = { + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId' }, + } as const + // @ts-expect-error the path params are missing + createTestRouter(withoutParams) + }) +}) diff --git a/e2e/react-router/route-testing/tests/setup.ts b/e2e/react-router/route-testing/tests/setup.ts new file mode 100644 index 0000000000..a30c326eeb --- /dev/null +++ b/e2e/react-router/route-testing/tests/setup.ts @@ -0,0 +1,14 @@ +import { cleanup } from '@testing-library/react' +import { afterEach, vi } from 'vitest' + +// @ts-expect-error React reads this flag to know that updates are wrapped in act(). +globalThis.IS_REACT_ACT_ENVIRONMENT = true + +// jsdom does not implement scrolling, which the router resets on navigation. +window.scrollTo = vi.fn() + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) diff --git a/e2e/react-router/route-testing/tests/user-menu.test.tsx b/e2e/react-router/route-testing/tests/user-menu.test.tsx new file mode 100644 index 0000000000..dd4e552810 --- /dev/null +++ b/e2e/react-router/route-testing/tests/user-menu.test.tsx @@ -0,0 +1,62 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/react' +import { RouterProvider } from '@tanstack/react-router' +import { createIsolatedTestRouter } from '@tanstack/react-router/testing' +import { describe, expect, test } from 'vitest' +import { UserMenu } from '../src/components/UserMenu' +import { routeTree } from '../src/routeTree.gen' +import { createPost, signedInContext } from '../src/test-fixtures' + +describe('a component bound to a layout route', () => { + test('is rendered through a child route and reads the state of the layout route', async () => { + const router = await createIsolatedTestRouter({ + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: 'post-1' }, + context: { ...signedInContext, user: { id: 'user-9', name: 'Grace' } }, + loaderData: { + '/_authed': { unreadCount: 7 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }) + render() + + const menu = screen.getByLabelText('User menu') + expect(menu.textContent).toContain('Grace') + expect(menu.textContent).toContain('7 unread') + }) + + test('navigating away changes the location and renders no other route', async () => { + const router = await createIsolatedTestRouter({ + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: 'post-1' }, + context: signedInContext, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }) + render() + + fireEvent.click(screen.getByRole('link', { name: 'Sign out' })) + + await waitFor(() => { + expect(router.state.location.pathname).toBe('/login') + }) + expect(screen.queryByRole('heading', { name: 'Sign in' })).toBeNull() + }) + + test('cannot be rendered in a layout route that its own path does not lead to', async () => { + await expect( + createIsolatedTestRouter({ + routeTree, + route: '/_authed', + element: , + context: signedInContext, + loaderData: { '/_authed': { unreadCount: 0 } }, + }), + ).rejects.toThrow('The route "/_authed" is not matched at "/"') + }) +}) diff --git a/e2e/react-router/route-testing/tsconfig.json b/e2e/react-router/route-testing/tsconfig.json new file mode 100644 index 0000000000..63c7715bb3 --- /dev/null +++ b/e2e/react-router/route-testing/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "react-jsx", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "skipLibCheck": true, + "resolveJsonModule": true, + "noEmit": true + }, + "include": ["src", "tests", "vite.config.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/react-router/route-testing/vite.config.ts b/e2e/react-router/route-testing/vite.config.ts new file mode 100644 index 0000000000..0e5ba9a175 --- /dev/null +++ b/e2e/react-router/route-testing/vite.config.ts @@ -0,0 +1,23 @@ +import { defineConfig } from 'vitest/config' +import react from '@vitejs/plugin-react' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ + target: 'react', + autoCodeSplitting: true, + }), + react(), + ], + test: { + watch: false, + environment: 'jsdom', + include: ['tests/**/*.test.tsx'], + setupFiles: ['./tests/setup.ts'], + typecheck: { + enabled: true, + include: ['tests/**/*.test-d.tsx'], + }, + }, +}) diff --git a/e2e/vue-router/route-testing/.gitignore b/e2e/vue-router/route-testing/.gitignore new file mode 100644 index 0000000000..2c5b3c96f1 --- /dev/null +++ b/e2e/vue-router/route-testing/.gitignore @@ -0,0 +1,4 @@ +node_modules +.DS_Store +dist +*.local diff --git a/e2e/vue-router/route-testing/package.json b/e2e/vue-router/route-testing/package.json new file mode 100644 index 0000000000..7f9171dd0a --- /dev/null +++ b/e2e/vue-router/route-testing/package.json @@ -0,0 +1,20 @@ +{ + "name": "tanstack-router-e2e-vue-route-testing", + "private": true, + "type": "module", + "scripts": { + "test:e2e": "vitest run" + }, + "dependencies": { + "@tanstack/router-plugin": "workspace:^", + "@tanstack/vue-router": "workspace:^", + "vue": "catalog:" + }, + "devDependencies": { + "@testing-library/vue": "^8.1.0", + "@vitejs/plugin-vue-jsx": "catalog:", + "jsdom": "catalog:", + "vite": "catalog:", + "vitest": "catalog:" + } +} diff --git a/e2e/vue-router/route-testing/src/api.ts b/e2e/vue-router/route-testing/src/api.ts new file mode 100644 index 0000000000..1d41b0c3e1 --- /dev/null +++ b/e2e/vue-router/route-testing/src/api.ts @@ -0,0 +1,35 @@ +export interface User { + id: string + name: string +} + +export interface Session { + user: User | null +} + +export interface Post { + id: string + title: string + authorId: string + status: 'draft' | 'published' +} + +async function getJson(url: string): Promise { + const response = await fetch(url) + if (!response.ok) { + throw new Error(`Request to ${url} failed with status ${response.status}`) + } + return response.json() as Promise +} + +export function fetchSession() { + return getJson('/api/session') +} + +export function fetchUnreadCount() { + return getJson('/api/notifications/unread-count') +} + +export function fetchPost(postId: string) { + return getJson(`/api/posts/${postId}`) +} diff --git a/e2e/vue-router/route-testing/src/components/PostHeader.tsx b/e2e/vue-router/route-testing/src/components/PostHeader.tsx new file mode 100644 index 0000000000..1ba9e152ee --- /dev/null +++ b/e2e/vue-router/route-testing/src/components/PostHeader.tsx @@ -0,0 +1,32 @@ +import { defineComponent } from 'vue' +import { Link, getRouteApi } from '@tanstack/vue-router' + +const postRoute = getRouteApi('/_authed/posts/$postId') + +export const PostHeader = defineComponent({ + setup() { + const data = postRoute.useLoaderData() + const context = postRoute.useRouteContext() + const search = postRoute.useSearch() + const params = postRoute.useParams() + + return () => ( +
+

{data.value.post.title}

+ {data.value.post.status === 'draft' ? Draft : null} + {data.value.post.authorId === context.value.user.id ? ( + Written by you + ) : null} + + {search.value.tab === 'details' ? 'Show comments' : 'Show details'} + +
+ ) + }, +}) diff --git a/e2e/vue-router/route-testing/src/components/UserMenu.tsx b/e2e/vue-router/route-testing/src/components/UserMenu.tsx new file mode 100644 index 0000000000..e61f46a825 --- /dev/null +++ b/e2e/vue-router/route-testing/src/components/UserMenu.tsx @@ -0,0 +1,19 @@ +import { defineComponent } from 'vue' +import { Link, getRouteApi } from '@tanstack/vue-router' + +const authedRoute = getRouteApi('/_authed') + +export const UserMenu = defineComponent({ + setup() { + const context = authedRoute.useRouteContext() + const data = authedRoute.useLoaderData() + + return () => ( +
+ {context.value.user.name} + {data.value.unreadCount} unread + Sign out +
+ ) + }, +}) diff --git a/e2e/vue-router/route-testing/src/routeTree.gen.ts b/e2e/vue-router/route-testing/src/routeTree.gen.ts new file mode 100644 index 0000000000..7dce9bb225 --- /dev/null +++ b/e2e/vue-router/route-testing/src/routeTree.gen.ts @@ -0,0 +1,119 @@ +/* eslint-disable */ + +// @ts-nocheck + +// noinspection JSUnusedGlobalSymbols + +// This file was automatically generated by TanStack Router. +// You should NOT make any changes in this file as it will be overwritten. +// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. + +import { Route as rootRouteImport } from './routes/__root' +import { Route as IndexRouteImport } from './routes/index' +import { Route as AuthedRouteImport } from './routes/_authed' +import { Route as LoginRouteImport } from './routes/login' +import { Route as AuthedPostsPostIdRouteImport } from './routes/_authed/posts.$postId' + +const IndexRoute = IndexRouteImport.update({ + id: '/', + path: '/', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedRoute = AuthedRouteImport.update({ + id: '/_authed', + getParentRoute: () => rootRouteImport, +} as any) +const LoginRoute = LoginRouteImport.update({ + id: '/login', + path: '/login', + getParentRoute: () => rootRouteImport, +} as any) +const AuthedPostsPostIdRoute = AuthedPostsPostIdRouteImport.update({ + id: '/posts/$postId', + path: '/posts/$postId', + getParentRoute: () => AuthedRoute, +} as any) + +export interface FileRoutesByFullPath { + '/': typeof IndexRoute + '/login': typeof LoginRoute + '/posts/$postId': typeof AuthedPostsPostIdRoute +} +export interface FileRoutesByTo { + '/': typeof IndexRoute + '/login': typeof LoginRoute + '/posts/$postId': typeof AuthedPostsPostIdRoute +} +export interface FileRoutesById { + __root__: typeof rootRouteImport + '/': typeof IndexRoute + '/_authed': typeof AuthedRouteWithChildren + '/login': typeof LoginRoute + '/_authed/posts/$postId': typeof AuthedPostsPostIdRoute +} +export interface FileRouteTypes { + fileRoutesByFullPath: FileRoutesByFullPath + fullPaths: '/' | '/login' | '/posts/$postId' + fileRoutesByTo: FileRoutesByTo + to: '/' | '/login' | '/posts/$postId' + id: '__root__' | '/' | '/_authed' | '/login' | '/_authed/posts/$postId' + fileRoutesById: FileRoutesById +} +export interface RootRouteChildren { + IndexRoute: typeof IndexRoute + AuthedRoute: typeof AuthedRouteWithChildren + LoginRoute: typeof LoginRoute +} + +declare module '@tanstack/vue-router' { + interface FileRoutesByPath { + '/': { + id: '/' + path: '/' + fullPath: '/' + preLoaderRoute: typeof IndexRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed': { + id: '/_authed' + path: '' + fullPath: '/' + preLoaderRoute: typeof AuthedRouteImport + parentRoute: typeof rootRouteImport + } + '/login': { + id: '/login' + path: '/login' + fullPath: '/login' + preLoaderRoute: typeof LoginRouteImport + parentRoute: typeof rootRouteImport + } + '/_authed/posts/$postId': { + id: '/_authed/posts/$postId' + path: '/posts/$postId' + fullPath: '/posts/$postId' + preLoaderRoute: typeof AuthedPostsPostIdRouteImport + parentRoute: typeof AuthedRoute + } + } +} + +interface AuthedRouteChildren { + AuthedPostsPostIdRoute: typeof AuthedPostsPostIdRoute +} + +const AuthedRouteChildren: AuthedRouteChildren = { + AuthedPostsPostIdRoute: AuthedPostsPostIdRoute, +} + +const AuthedRouteWithChildren = + AuthedRoute._addFileChildren(AuthedRouteChildren) + +const rootRouteChildren: RootRouteChildren = { + IndexRoute: IndexRoute, + AuthedRoute: AuthedRouteWithChildren, + LoginRoute: LoginRoute, +} +export const routeTree = rootRouteImport + ._addFileChildren(rootRouteChildren) + ._addFileTypes() diff --git a/e2e/vue-router/route-testing/src/router.tsx b/e2e/vue-router/route-testing/src/router.tsx new file mode 100644 index 0000000000..83e7b2e8e2 --- /dev/null +++ b/e2e/vue-router/route-testing/src/router.tsx @@ -0,0 +1,16 @@ +import { createRouter } from '@tanstack/vue-router' +import { routeTree } from './routeTree.gen' + +export function createAppRouter() { + return createRouter({ + routeTree, + context: { locale: 'en' }, + defaultPreload: 'intent', + }) +} + +declare module '@tanstack/vue-router' { + interface Register { + router: ReturnType + } +} diff --git a/e2e/vue-router/route-testing/src/routes/__root.tsx b/e2e/vue-router/route-testing/src/routes/__root.tsx new file mode 100644 index 0000000000..e6f8dcb36e --- /dev/null +++ b/e2e/vue-router/route-testing/src/routes/__root.tsx @@ -0,0 +1,25 @@ +import { defineComponent } from 'vue' +import { Link, Outlet, createRootRouteWithContext } from '@tanstack/vue-router' +import { fetchSession } from '../api' + +export interface RouterContext { + locale: string +} + +const RootComponent = defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createRootRouteWithContext()({ + beforeLoad: async () => ({ session: await fetchSession() }), + component: RootComponent, +}) diff --git a/e2e/vue-router/route-testing/src/routes/_authed.tsx b/e2e/vue-router/route-testing/src/routes/_authed.tsx new file mode 100644 index 0000000000..35dee48d81 --- /dev/null +++ b/e2e/vue-router/route-testing/src/routes/_authed.tsx @@ -0,0 +1,26 @@ +import { defineComponent } from 'vue' +import { Outlet, createFileRoute, redirect } from '@tanstack/vue-router' +import { fetchUnreadCount } from '../api' +import { UserMenu } from '../components/UserMenu' + +const AuthedLayout = defineComponent({ + setup() { + return () => ( + <> + + + + ) + }, +}) + +export const Route = createFileRoute('/_authed')({ + beforeLoad: ({ context, location }) => { + if (!context.session.user) { + throw redirect({ to: '/login', search: { redirect: location.href } }) + } + return { user: context.session.user } + }, + loader: async () => ({ unreadCount: await fetchUnreadCount() }), + component: AuthedLayout, +}) diff --git a/e2e/vue-router/route-testing/src/routes/_authed/posts.$postId.tsx b/e2e/vue-router/route-testing/src/routes/_authed/posts.$postId.tsx new file mode 100644 index 0000000000..df387604bc --- /dev/null +++ b/e2e/vue-router/route-testing/src/routes/_authed/posts.$postId.tsx @@ -0,0 +1,38 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import { fetchPost } from '../../api' +import { PostHeader } from '../../components/PostHeader' +import type { SearchSchemaInput } from '@tanstack/vue-router' + +export type PostTab = 'details' | 'comments' + +const PostPage = defineComponent({ + setup() { + const search = Route.useSearch() + + return () => ( +
+ +
+ {search.value.tab === 'comments' ? 'Comments' : 'Details'} +
+
+ ) + }, +}) + +export const Route = createFileRoute('/_authed/posts/$postId')({ + validateSearch: ( + search: { tab?: string } & SearchSchemaInput, + ): { tab: PostTab } => { + if (search.tab === undefined || search.tab === 'details') { + return { tab: 'details' } + } + if (search.tab === 'comments') { + return { tab: 'comments' } + } + throw new Error(`Unknown tab "${search.tab}"`) + }, + loader: async ({ params }) => ({ post: await fetchPost(params.postId) }), + component: PostPage, +}) diff --git a/e2e/vue-router/route-testing/src/routes/index.tsx b/e2e/vue-router/route-testing/src/routes/index.tsx new file mode 100644 index 0000000000..49286a3ac8 --- /dev/null +++ b/e2e/vue-router/route-testing/src/routes/index.tsx @@ -0,0 +1,19 @@ +import { defineComponent } from 'vue' +import { Link, createFileRoute } from '@tanstack/vue-router' + +const HomePage = defineComponent({ + setup() { + return () => ( +
+

Home

+ + First post + +
+ ) + }, +}) + +export const Route = createFileRoute('/')({ + component: HomePage, +}) diff --git a/e2e/vue-router/route-testing/src/routes/login.tsx b/e2e/vue-router/route-testing/src/routes/login.tsx new file mode 100644 index 0000000000..c5ccf2e5b3 --- /dev/null +++ b/e2e/vue-router/route-testing/src/routes/login.tsx @@ -0,0 +1,26 @@ +import { defineComponent } from 'vue' +import { createFileRoute } from '@tanstack/vue-router' +import type { SearchSchemaInput } from '@tanstack/vue-router' + +const LoginPage = defineComponent({ + setup() { + const search = Route.useSearch() + + return () => ( +
+

Sign in

+ {search.value.redirect ? ( +

You will return to {search.value.redirect}

+ ) : null} +
+ ) + }, +}) + +export const Route = createFileRoute('/login')({ + validateSearch: ( + search: { redirect?: string } & SearchSchemaInput, + ): { redirect?: string } => + typeof search.redirect === 'string' ? { redirect: search.redirect } : {}, + component: LoginPage, +}) diff --git a/e2e/vue-router/route-testing/src/test-fixtures.ts b/e2e/vue-router/route-testing/src/test-fixtures.ts new file mode 100644 index 0000000000..047a9f5d26 --- /dev/null +++ b/e2e/vue-router/route-testing/src/test-fixtures.ts @@ -0,0 +1,20 @@ +import type { Post, User } from './api' + +export const testUser: User = { id: 'user-1', name: 'Ada' } + +export function createPost(overrides: Partial = {}): Post { + return { + id: 'post-1', + title: 'Hello world', + authorId: 'user-2', + status: 'published', + ...overrides, + } +} + +/** The context of the routes under `/_authed` for a signed-in test user. */ +export const signedInContext = { + locale: 'en', + session: { user: testUser }, + user: testUser, +} diff --git a/e2e/vue-router/route-testing/tests/post-header.test.tsx b/e2e/vue-router/route-testing/tests/post-header.test.tsx new file mode 100644 index 0000000000..2179c93d29 --- /dev/null +++ b/e2e/vue-router/route-testing/tests/post-header.test.tsx @@ -0,0 +1,118 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/vue' +import { RouterProvider } from '@tanstack/vue-router' +import { createIsolatedTestRouter } from '@tanstack/vue-router/testing' +import { describe, expect, test, vi } from 'vitest' +import { PostHeader } from '../src/components/PostHeader' +import { routeTree } from '../src/routeTree.gen' +import { createPost, signedInContext, testUser } from '../src/test-fixtures' + +const postRoute = { + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: 'post-1' }, + context: signedInContext, +} as const + +describe('a component rendered in its route with supplied state', () => { + test('reads loader data, context, search and params of the route', async () => { + const router = await createIsolatedTestRouter({ + ...postRoute, + loaderData: { + '/_authed': { unreadCount: 2 }, + '/_authed/posts/$postId': { + post: createPost({ title: 'Typed tests', authorId: testUser.id }), + }, + }, + }) + render() + + expect(screen.getByRole('heading').textContent).toBe('Typed tests') + expect(screen.getByText('Written by you')).toBeTruthy() + expect(screen.queryByText('Draft')).toBeNull() + + const link = screen.getByRole('link', { name: 'Show comments' }) + expect(link.getAttribute('href')).toBe('/posts/post-1?tab=comments') + }) + + test('runs no lifecycle of the application and renders none of its layout', async () => { + const fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) + + const router = await createIsolatedTestRouter({ + ...postRoute, + loaderData: { + '/_authed': { unreadCount: 2 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }) + render() + + expect(fetchMock).not.toHaveBeenCalled() + expect(screen.queryByRole('navigation')).toBeNull() + expect(screen.queryByLabelText('User menu')).toBeNull() + expect(screen.queryByLabelText('Tab content')).toBeNull() + }) + + test('shows the state the test supplies', async () => { + const router = await createIsolatedTestRouter({ + ...postRoute, + context: { ...signedInContext, user: { id: 'user-2', name: 'Grace' } }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost({ status: 'draft' }) }, + }, + }) + render() + + expect(screen.getByText('Draft')).toBeTruthy() + expect(screen.getByText('Written by you')).toBeTruthy() + }) + + test('sends search params through the validateSearch of the route', async () => { + const router = await createIsolatedTestRouter({ + ...postRoute, + search: { tab: 'comments' }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }) + render() + + expect(screen.getByRole('link', { name: 'Show details' })).toBeTruthy() + }) + + test('fails when the search params do not pass validateSearch', async () => { + await expect( + createIsolatedTestRouter({ + ...postRoute, + search: { tab: 'history' }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }), + ).rejects.toThrow('Unknown tab "history"') + }) + + test('navigates with the real router', async () => { + const router = await createIsolatedTestRouter({ + ...postRoute, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }) + render() + + await fireEvent.click(screen.getByRole('link', { name: 'Show comments' })) + + await waitFor(() => { + expect(router.state.location.search).toEqual({ tab: 'comments' }) + }) + expect( + await screen.findByRole('link', { name: 'Show details' }), + ).toBeTruthy() + }) +}) diff --git a/e2e/vue-router/route-testing/tests/post-route.test.tsx b/e2e/vue-router/route-testing/tests/post-route.test.tsx new file mode 100644 index 0000000000..b1f840d397 --- /dev/null +++ b/e2e/vue-router/route-testing/tests/post-route.test.tsx @@ -0,0 +1,154 @@ +import { render, screen, waitFor } from '@testing-library/vue' +import { RouterProvider, rootRouteId } from '@tanstack/vue-router' +import { createTestRouter } from '@tanstack/vue-router/testing' +import { describe, expect, test, vi } from 'vitest' +import { routeTree } from '../src/routeTree.gen' +import { createPost, testUser } from '../src/test-fixtures' +import type { Session } from '../src/api' + +function stubApi(responses: Record) { + const fetchMock = vi.fn((input: string | URL | Request) => { + const url = String(input) + return Promise.resolve( + url in responses + ? new Response(JSON.stringify(responses[url])) + : new Response('Not found', { status: 404 }), + ) + }) + vi.stubGlobal('fetch', fetchMock) + return fetchMock +} + +describe('a test router over the route tree of the application', () => { + test('runs the lifecycle of the application by default', async () => { + const fetchMock = stubApi({ + '/api/session': { user: testUser } satisfies Session, + '/api/notifications/unread-count': 3, + '/api/posts/post-1': createPost({ title: 'From the API' }), + }) + + const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + }) + render() + + expect( + await screen.findByRole('heading', { name: 'From the API' }), + ).toBeTruthy() + expect(screen.getByRole('navigation', { name: 'Main' })).toBeTruthy() + expect(screen.getByLabelText('User menu').textContent).toContain('3 unread') + expect(screen.getByLabelText('Tab content').textContent).toBe('Details') + expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([ + '/api/session', + '/api/notifications/unread-count', + '/api/posts/post-1', + ]) + }) + + test('follows the redirect of a real beforeLoad', async () => { + stubApi({ '/api/session': { user: null } satisfies Session }) + + const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { + to: '/posts/$postId', + params: { postId: 'post-1' }, + search: { tab: 'comments' }, + }, + }) + render() + + expect(await screen.findByRole('heading', { name: 'Sign in' })).toBeTruthy() + expect(router.state.location.pathname).toBe('/login') + expect(router.state.location.search).toEqual({ + redirect: '/posts/post-1?tab=comments', + }) + }) + + test('replaces only the lifecycle options a test names', async () => { + const fetchMock = stubApi({}) + + const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-7' } }, + overrides: { + // A seed: the session lookup of the root route does not run. + [rootRouteId]: { routeContext: { session: { user: testUser } } }, + // A seed for the loader data. + '/_authed': { loaderData: { unreadCount: 5 } }, + // A replacement, typed like the loader of the route. + '/_authed/posts/$postId': { + loader: ({ params }) => ({ + post: createPost({ id: params.postId, title: 'From the test' }), + }), + }, + }, + }) + render() + + expect( + await screen.findByRole('heading', { name: 'From the test' }), + ).toBeTruthy() + // The beforeLoad of `/_authed` is not named, so the real one derived the + // user from the seeded session. + const menu = screen.getByLabelText('User menu') + expect(menu.textContent).toContain(testUser.name) + expect(menu.textContent).toContain('5 unread') + expect(fetchMock).not.toHaveBeenCalled() + }) + + test('replaces what a route renders', async () => { + stubApi({ + '/api/session': { user: testUser } satisfies Session, + '/api/notifications/unread-count': 0, + }) + + const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + overrides: { + '/_authed/posts/$postId': { + loaderData: { post: createPost() }, + component: () =>

Replaced page

, + }, + }, + }) + render() + + expect(await screen.findByText('Replaced page')).toBeTruthy() + expect(screen.queryByLabelText('Tab content')).toBeNull() + }) + + test('keeps overrides out of the next router', async () => { + const first = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: testUser } } }, + '/_authed': { loaderData: { unreadCount: 0 } }, + '/_authed/posts/$postId': { loaderData: { post: createPost() } }, + }, + }) + await first.load() + expect(first.state.matches.at(-1)?.status).toBe('success') + + const fetchMock = stubApi({ '/api/session': { user: null } }) + const second = createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + }) + await second.load() + + await waitFor(() => { + expect(second.state.location.pathname).toBe('/login') + }) + expect(fetchMock).toHaveBeenCalledWith('/api/session') + }) +}) diff --git a/e2e/vue-router/route-testing/tests/route-testing.test-d.tsx b/e2e/vue-router/route-testing/tests/route-testing.test-d.tsx new file mode 100644 index 0000000000..fa4c43e486 --- /dev/null +++ b/e2e/vue-router/route-testing/tests/route-testing.test-d.tsx @@ -0,0 +1,136 @@ +import { rootRouteId } from '@tanstack/vue-router' +import { + createIsolatedTestRouter, + createTestRouter, +} from '@tanstack/vue-router/testing' +import { describe, expectTypeOf, test } from 'vitest' +import { PostHeader } from '../src/components/PostHeader' +import { routeTree } from '../src/routeTree.gen' +import { createPost, signedInContext, testUser } from '../src/test-fixtures' +import type { Post, Session, User } from '../src/api' + +const postState = { + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: 'post-1' }, + context: signedInContext, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, +} as const + +describe('createIsolatedTestRouter is typed from the generated route tree', () => { + test('accepts the complete state of a route', () => { + void createIsolatedTestRouter(postState) + }) + + test('rejects a missing context value', () => { + const withoutUser = { + ...postState, + context: { locale: 'en', session: { user: testUser } }, + } as const + // @ts-expect-error `user` comes from the beforeLoad of `/_authed` and is missing + void createIsolatedTestRouter(withoutUser) + }) + + test('rejects missing loader data of the route and of its ancestors', () => { + const withoutRouteData = { + ...postState, + loaderData: { '/_authed': { unreadCount: 0 } }, + } as const + // @ts-expect-error the loader data of the route is missing + void createIsolatedTestRouter(withoutRouteData) + + const withoutAncestorData = { + ...postState, + loaderData: { '/_authed/posts/$postId': { post: createPost() } }, + } as const + // @ts-expect-error the loader data of `/_authed` is missing + void createIsolatedTestRouter(withoutAncestorData) + }) + + test('rejects loader data of the wrong shape', () => { + const wrongPost = { + ...postState, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { + post: { id: 'post-1', title: 'No status' }, + }, + }, + } as const + // @ts-expect-error `authorId` and `status` are missing from the post + void createIsolatedTestRouter(wrongPost) + }) + + test('rejects a route id that is not in the tree', () => { + const unknownRoute = { ...postState, route: '/posts/$postId' } as const + // @ts-expect-error the id of the route is `/_authed/posts/$postId` + void createIsolatedTestRouter(unknownRoute) + }) + + test('takes the root route by rootRouteId', () => { + void createIsolatedTestRouter({ + routeTree, + route: rootRouteId, + element: , + context: { locale: 'en', session: { user: testUser } }, + }) + }) +}) + +describe('createTestRouter is typed from the generated route tree', () => { + test('types a replacement like the option it replaces', () => { + createTestRouter({ + routeTree, + context: { locale: 'en' }, + overrides: { + [rootRouteId]: { + beforeLoad: ({ context }) => { + expectTypeOf(context).toEqualTypeOf<{ locale: string }>() + return { session: { user: testUser } } + }, + }, + '/_authed': { + beforeLoad: ({ context }) => { + expectTypeOf(context.session).toEqualTypeOf() + return { user: testUser } + }, + }, + '/_authed/posts/$postId': { + loader: ({ params, context }) => { + expectTypeOf(params).toEqualTypeOf<{ postId: string }>() + expectTypeOf(context.user).toEqualTypeOf() + return { post: createPost({ id: params.postId }) } + }, + }, + }, + }) + }) + + test('rejects a replacement that returns the wrong data', () => { + const wrongLoader = { + routeTree, + context: { locale: 'en' }, + overrides: { + '/_authed/posts/$postId': { + loader: (): { post: Pick } => ({ post: { id: '1' } }), + }, + }, + } + // @ts-expect-error the loader has to return a whole post + createTestRouter(wrongLoader) + }) + + test('types the start location like a link', () => { + const withoutParams = { + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId' }, + } as const + // @ts-expect-error the path params are missing + createTestRouter(withoutParams) + }) +}) diff --git a/e2e/vue-router/route-testing/tests/setup.ts b/e2e/vue-router/route-testing/tests/setup.ts new file mode 100644 index 0000000000..7d114406d8 --- /dev/null +++ b/e2e/vue-router/route-testing/tests/setup.ts @@ -0,0 +1,11 @@ +import { cleanup } from '@testing-library/vue' +import { afterEach, vi } from 'vitest' + +// jsdom does not implement scrolling, which the router resets on navigation. +window.scrollTo = vi.fn() + +afterEach(() => { + cleanup() + vi.restoreAllMocks() + vi.unstubAllGlobals() +}) diff --git a/e2e/vue-router/route-testing/tests/user-menu.test.tsx b/e2e/vue-router/route-testing/tests/user-menu.test.tsx new file mode 100644 index 0000000000..6afd9a7b7e --- /dev/null +++ b/e2e/vue-router/route-testing/tests/user-menu.test.tsx @@ -0,0 +1,62 @@ +import { fireEvent, render, screen, waitFor } from '@testing-library/vue' +import { RouterProvider } from '@tanstack/vue-router' +import { createIsolatedTestRouter } from '@tanstack/vue-router/testing' +import { describe, expect, test } from 'vitest' +import { UserMenu } from '../src/components/UserMenu' +import { routeTree } from '../src/routeTree.gen' +import { createPost, signedInContext } from '../src/test-fixtures' + +describe('a component bound to a layout route', () => { + test('is rendered through a child route and reads the state of the layout route', async () => { + const router = await createIsolatedTestRouter({ + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: 'post-1' }, + context: { ...signedInContext, user: { id: 'user-9', name: 'Grace' } }, + loaderData: { + '/_authed': { unreadCount: 7 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }) + render() + + const menu = screen.getByLabelText('User menu') + expect(menu.textContent).toContain('Grace') + expect(menu.textContent).toContain('7 unread') + }) + + test('navigating away changes the location and renders no other route', async () => { + const router = await createIsolatedTestRouter({ + routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: 'post-1' }, + context: signedInContext, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, + }) + render() + + await fireEvent.click(screen.getByRole('link', { name: 'Sign out' })) + + await waitFor(() => { + expect(router.state.location.pathname).toBe('/login') + }) + expect(screen.queryByRole('heading', { name: 'Sign in' })).toBeNull() + }) + + test('cannot be rendered in a layout route that its own path does not lead to', async () => { + await expect( + createIsolatedTestRouter({ + routeTree, + route: '/_authed', + element: , + context: signedInContext, + loaderData: { '/_authed': { unreadCount: 0 } }, + }), + ).rejects.toThrow('The route "/_authed" is not matched at "/"') + }) +}) diff --git a/e2e/vue-router/route-testing/tsconfig.json b/e2e/vue-router/route-testing/tsconfig.json new file mode 100644 index 0000000000..833d9f305d --- /dev/null +++ b/e2e/vue-router/route-testing/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "strict": true, + "esModuleInterop": true, + "jsx": "preserve", + "jsxImportSource": "vue", + "target": "ESNext", + "moduleResolution": "Bundler", + "module": "ESNext", + "skipLibCheck": true, + "resolveJsonModule": true, + "noEmit": true + }, + "include": ["src", "tests", "vite.config.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/e2e/vue-router/route-testing/vite.config.ts b/e2e/vue-router/route-testing/vite.config.ts new file mode 100644 index 0000000000..2430f3bb9c --- /dev/null +++ b/e2e/vue-router/route-testing/vite.config.ts @@ -0,0 +1,23 @@ +import { defineConfig } from 'vitest/config' +import vueJsx from '@vitejs/plugin-vue-jsx' +import { tanstackRouter } from '@tanstack/router-plugin/vite' + +export default defineConfig({ + plugins: [ + tanstackRouter({ + target: 'vue', + autoCodeSplitting: true, + }), + vueJsx(), + ], + test: { + watch: false, + environment: 'jsdom', + include: ['tests/**/*.test.tsx'], + setupFiles: ['./tests/setup.ts'], + typecheck: { + enabled: true, + include: ['tests/**/*.test-d.tsx'], + }, + }, +}) diff --git a/packages/react-router/package.json b/packages/react-router/package.json index 9a61d5af25..e3d5c6e3d0 100644 --- a/packages/react-router/package.json +++ b/packages/react-router/package.json @@ -81,6 +81,16 @@ "default": "./dist/cjs/ssr/client.cjs" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing.d.ts", + "default": "./dist/esm/testing.js" + }, + "require": { + "types": "./dist/cjs/testing.d.cts", + "default": "./dist/cjs/testing.cjs" + } + }, "./package.json": "./package.json" }, "sideEffects": false, diff --git a/packages/react-router/src/testing.ts b/packages/react-router/src/testing.ts new file mode 100644 index 0000000000..31a501e044 --- /dev/null +++ b/packages/react-router/src/testing.ts @@ -0,0 +1,161 @@ +import { + createIsolatedTestRouterWith, + createTestRouterWith, +} from '@tanstack/router-core/testing' +import { createRouter } from './router' +import type * as React from 'react' +import type { RouterHistory } from '@tanstack/history' +import type { AnyRoute, TrailingSlashOption } from '@tanstack/router-core' +import type { + RouteTestOverrides as CoreRouteTestOverrides, + IsolatedTestRouterOptions, + TestRouterOptions, +} from '@tanstack/router-core/testing' +import type { + ErrorRouteComponent, + NotFoundRouteComponent, + RouteComponent, +} from './route' +import type { Router } from './router' + +export type { + IsolatedRouteState, + RouteTestBeforeLoadFn, + RouteTestContextFn, + RouteTestLoaderFn, +} from '@tanstack/router-core/testing' + +/** The component options a test can replace on a route. */ +export interface RouteTestComponents { + component?: RouteComponent + pendingComponent?: RouteComponent + errorComponent?: false | null | undefined | ErrorRouteComponent + notFoundComponent?: NotFoundRouteComponent +} + +/** + * Overrides by route id, typed from the route tree. The root route's id is + * `rootRouteId`, used as a computed key: `{ [rootRouteId]: { ... } }`. + */ +export type RouteTestOverrides = + CoreRouteTestOverrides + +/** The options of `createTestRouter`: those of `createRouter`, plus `location` and `overrides`. */ +export type CreateTestRouterOptions< + TRouteTree extends AnyRoute, + TLocation = unknown, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, + TRouterHistory extends RouterHistory = RouterHistory, + TDehydrated extends Record = Record, +> = TestRouterOptions< + TRouteTree, + TLocation, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated, + RouteTestComponents +> + +/** The options of `createIsolatedTestRouter`. */ +export type CreateIsolatedTestRouterOptions< + TRouteTree extends AnyRoute, + TId, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, +> = IsolatedTestRouterOptions< + TRouteTree, + TId, + React.ReactElement, + TTrailingSlashOption, + TDefaultStructuralSharingOption +> + +/** + * Creates a router for a test, over a copy of the route tree. It takes the + * options of `createRouter`, plus `location` and `overrides`. Every route runs + * the application's own options unless `overrides` replaces them. Without a + * `history`, the router uses a memory history. + * + * The router has not loaded yet. Render it with `RouterProvider`, or call + * `router.load()` first. + * + * ```tsx + * const router = createTestRouter({ + * routeTree, + * context: { queryClient }, + * location: { to: '/posts/$postId', params: { postId: '1' } }, + * overrides: { '/posts/$postId': { loaderData: { post } } }, + * }) + * render() + * ``` + */ +export function createTestRouter< + TRouteTree extends AnyRoute, + const TLocation = unknown, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, + TRouterHistory extends RouterHistory = RouterHistory, + TDehydrated extends Record = Record, +>( + options: CreateTestRouterOptions< + TRouteTree, + TLocation, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated + >, +): Router< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated +> { + return createTestRouterWith(createRouter, options as any) as any +} + +/** + * Creates a router that renders one element inside one route, with the state + * the test supplies. It resolves once the router has loaded, so the first + * render of `` is complete. + * + * No `context`, `beforeLoad` or `loader` of any route runs, and no route + * component renders. The options are typed from the route: they ask for the + * context and the loader data those options would have produced. + * + * ```tsx + * const router = await createIsolatedTestRouter({ + * routeTree, + * route: '/posts/$postId', + * element: , + * params: { postId: '1' }, + * loaderData: { '/posts/$postId': { post } }, + * }) + * render() + * ``` + */ +export function createIsolatedTestRouter< + TRouteTree extends AnyRoute, + // `IsolatedTestRouterOptions` checks that `route` is a route id of the tree. + const TId extends string, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, +>( + options: CreateIsolatedTestRouterOptions< + TRouteTree, + TId, + TTrailingSlashOption, + TDefaultStructuralSharingOption + >, +): Promise< + Router +> { + const { element, ...state } = options as any + return createIsolatedTestRouterWith(createRouter, { + ...state, + component: () => element, + }) as any +} diff --git a/packages/react-router/tests/testing.test-d.tsx b/packages/react-router/tests/testing.test-d.tsx new file mode 100644 index 0000000000..3e9b83dac9 --- /dev/null +++ b/packages/react-router/tests/testing.test-d.tsx @@ -0,0 +1,337 @@ +import { describe, expectTypeOf, test } from 'vitest' +import { createRootRouteWithContext, createRoute, rootRouteId } from '../src' +import { createIsolatedTestRouter, createTestRouter } from '../src/testing' +import type { Router, SearchSchemaInput } from '../src' +import type { IsolatedRouteState, RouteTestOverrides } from '../src/testing' + +interface User { + id: string +} + +interface Session { + user: User | null +} + +const rootRoute = createRootRouteWithContext<{ locale: string }>()({ + beforeLoad: (): { session: Session } => ({ session: { user: null } }), +}) + +const authedRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authed', + beforeLoad: ({ context }) => ({ user: context.session.user as User }), + loader: () => ({ unreadCount: 1 }), +}) + +const postRoute = createRoute({ + getParentRoute: () => authedRoute, + path: '/posts/$postId', + validateSearch: (search: { tab?: string } & SearchSchemaInput) => ({ + tab: search.tab ?? 'details', + }), + loaderDeps: ({ search }) => ({ tab: search.tab }), + loader: ({ params }) => ({ post: { id: params.postId } }), +}) + +const settingsRoute = createRoute({ + getParentRoute: () => authedRoute, + path: '/settings', +}) + +const loginRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/login', + beforeLoad: () => { + // A guard that adds nothing to the context. + }, +}) + +const routeTree = rootRoute.addChildren([ + authedRoute.addChildren([postRoute, settingsRoute]), + loginRoute, +]) + +type RouteTree = typeof routeTree + +type RequiredKeys = { + [K in keyof T]-?: {} extends Pick ? never : K +}[keyof T] + +const postState = { + routeTree, + route: '/_authed/posts/$postId', + element:
, + params: { postId: '1' }, + context: { locale: 'en', session: { user: null }, user: { id: '1' } }, + loaderData: { + '/_authed': { unreadCount: 1 }, + '/_authed/posts/$postId': { post: { id: '1' } }, + }, +} as const + +describe('createIsolatedTestRouter', () => { + test('asks for everything the route promises to its components', () => { + type PostState = IsolatedRouteState + + expectTypeOf>().toEqualTypeOf< + 'route' | 'params' | 'context' | 'loaderData' + >() + expectTypeOf().toEqualTypeOf<'/_authed/posts/$postId'>() + expectTypeOf().toEqualTypeOf<'postId'>() + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf< + 'locale' | 'session' | 'user' + >() + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() + expectTypeOf>().toEqualTypeOf< + '/_authed' | '/_authed/posts/$postId' + >() + expectTypeOf().toEqualTypeOf<{ + unreadCount: number + }>() + expectTypeOf< + PostState['loaderData']['/_authed/posts/$postId'] + >().toEqualTypeOf<{ post: { id: string } }>() + expectTypeOf>().toEqualTypeOf<{ + tab?: string + }>() + }) + + test('asks for nothing a route does not have', () => { + type SettingsState = IsolatedRouteState + // No path params and no loader of its own, but an ancestor with a loader. + expectTypeOf>().toEqualTypeOf< + 'route' | 'context' | 'loaderData' + >() + expectTypeOf< + RequiredKeys + >().toEqualTypeOf<'/_authed'>() + + type LoginState = IsolatedRouteState + // Its beforeLoad adds nothing, so the context is the one of the root route. + expectTypeOf>().toEqualTypeOf< + 'route' | 'context' + >() + expectTypeOf().toEqualTypeOf< + 'locale' | 'session' + >() + const _loginState: LoginState = { + // @ts-expect-error the state of `/login` cannot name another route + route: '/_authed/posts/$postId', + context: { locale: 'en', session: { user: null } }, + } + }) + + test('accepts the complete state and resolves to the router type', () => { + expectTypeOf(createIsolatedTestRouter(postState)).toEqualTypeOf< + Promise> + >() + }) + + test('rejects state that is incomplete or of the wrong type', () => { + const { context: _context, ...withoutContext } = postState + // @ts-expect-error the context of the route is missing + void createIsolatedTestRouter(withoutContext) + + const withoutUser = { + ...postState, + context: { locale: 'en', session: { user: null } }, + } as const + // @ts-expect-error `user` is missing from the context + void createIsolatedTestRouter(withoutUser) + + const withoutRouteLoaderData = { + ...postState, + loaderData: { '/_authed': { unreadCount: 1 } }, + } as const + // @ts-expect-error the loader data of the route is missing + void createIsolatedTestRouter(withoutRouteLoaderData) + + const withoutAncestorLoaderData = { + ...postState, + loaderData: { '/_authed/posts/$postId': { post: { id: '1' } } }, + } as const + // @ts-expect-error the loader data of `/_authed` is missing + void createIsolatedTestRouter(withoutAncestorLoaderData) + + const { params: _params, ...withoutParams } = postState + // @ts-expect-error the path params are missing + void createIsolatedTestRouter(withoutParams) + + const wrongLoaderData = { + ...postState, + loaderData: { + '/_authed': { unreadCount: 1 }, + '/_authed/posts/$postId': { post: 1 }, + }, + } as const + // @ts-expect-error `post` is not a number + void createIsolatedTestRouter(wrongLoaderData) + + const unknownRoute = { ...postState, route: '/unknown' } as const + // @ts-expect-error not a route id of the tree + void createIsolatedTestRouter(unknownRoute) + }) + + test('takes the root route by rootRouteId', () => { + type RootState = IsolatedRouteState + expectTypeOf>().toEqualTypeOf<'route' | 'context'>() + + void createIsolatedTestRouter({ + routeTree, + route: rootRouteId, + element:
, + context: { locale: 'en', session: { user: null } }, + }) + }) +}) + +describe('createTestRouter', () => { + test('returns the router type of the route tree', () => { + expectTypeOf( + createTestRouter({ routeTree, context: { locale: 'en' } }), + ).toEqualTypeOf>() + }) + + test('requires the router context like createRouter', () => { + const withoutContext = { routeTree } as const + // @ts-expect-error the router context is required + createTestRouter(withoutContext) + }) + + test('types the location like navigation options', () => { + createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { + to: '/posts/$postId', + params: { postId: '1' }, + search: { tab: 'comments' }, + }, + }) + + const withoutParams = { + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId' }, + } as const + // @ts-expect-error the path params of the location are missing + createTestRouter(withoutParams) + + const unknownPath = { + routeTree, + context: { locale: 'en' }, + location: { to: '/unknown' }, + } as const + // @ts-expect-error not a path of the tree + createTestRouter(unknownPath) + }) + + test('types replacements and seeds from the route', () => { + createTestRouter({ + routeTree, + context: { locale: 'en' }, + overrides: { + [rootRouteId]: { + beforeLoad: ({ context }) => { + expectTypeOf(context.locale).toEqualTypeOf() + return { session: { user: null } } + }, + }, + '/_authed': { + beforeLoad: ({ context }) => { + expectTypeOf(context.locale).toEqualTypeOf() + expectTypeOf(context.session).toEqualTypeOf() + return { user: { id: '1' } } + }, + loaderData: { unreadCount: 2 }, + }, + '/_authed/posts/$postId': { + loader: ({ params, context, deps }) => { + expectTypeOf(params).toEqualTypeOf<{ postId: string }>() + expectTypeOf(context.user).toEqualTypeOf() + expectTypeOf(deps).toEqualTypeOf<{ tab: string }>() + return { post: { id: params.postId } } + }, + component: () =>
, + }, + '/login': { + beforeLoad: () => {}, + }, + }, + }) + + createTestRouter({ + routeTree, + context: { locale: 'en' }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: { id: '1' } } } }, + }, + }) + }) + + test('checks a shared override object with RouteTestOverrides', () => { + const signedIn = { + [rootRouteId]: { routeContext: { session: { user: { id: '1' } } } }, + } satisfies RouteTestOverrides + + createTestRouter({ + routeTree, + context: { locale: 'en' }, + overrides: signedIn, + }) + }) + + test('rejects replacements and seeds of the wrong type', () => { + const wrongSeed = { + routeTree, + context: { locale: 'en' }, + overrides: { '/_authed': { loaderData: { unreadCount: 'many' } } }, + } as const + // @ts-expect-error `unreadCount` is a number + createTestRouter(wrongSeed) + + const wrongContextSeed = { + routeTree, + context: { locale: 'en' }, + overrides: { '/_authed': { routeContext: { user: 'nobody' } } }, + } as const + // @ts-expect-error `user` is an object + createTestRouter(wrongContextSeed) + + const contextValue = { + routeTree, + context: { locale: 'en' }, + overrides: { '/_authed': { context: { user: { id: '1' } } } }, + } as const + // @ts-expect-error `context` replaces the route option and takes a function + createTestRouter(contextValue) + + const wrongLoader = { + routeTree, + context: { locale: 'en' }, + overrides: { + '/_authed/posts/$postId': { loader: () => ({ post: 'none' }) }, + }, + } + // @ts-expect-error the loader has to return the loader data of the route + createTestRouter(wrongLoader) + + const wrongBeforeLoad = { + routeTree, + context: { locale: 'en' }, + overrides: { '/_authed': { beforeLoad: () => ({ user: 'nobody' }) } }, + } + // @ts-expect-error beforeLoad has to return what the route's own returns + createTestRouter(wrongBeforeLoad) + + const unknownRoute = { + routeTree, + context: { locale: 'en' }, + overrides: { '/unknown': {} }, + } as const + // @ts-expect-error not a route id of the tree + createTestRouter(unknownRoute) + }) +}) diff --git a/packages/react-router/tests/testing.test.tsx b/packages/react-router/tests/testing.test.tsx new file mode 100644 index 0000000000..f64a63176f --- /dev/null +++ b/packages/react-router/tests/testing.test.tsx @@ -0,0 +1,654 @@ +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { afterEach, describe, expect, test, vi } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createLazyRoute, + createMemoryHistory, + createRootRouteWithContext, + createRoute, + redirect, + rootRouteId, +} from '../src' +import { createIsolatedTestRouter, createTestRouter } from '../src/testing' +import type { SearchSchemaInput } from '../src' + +afterEach(() => { + cleanup() +}) + +interface User { + id: string + name: string +} + +interface Session { + user: User | null +} + +interface Post { + id: string + title: string +} + +const realUser: User = { id: 'real', name: 'Real user' } +const testUser: User = { id: 'test', name: 'Test user' } + +function createApp() { + const calls: Array = [] + const loadLazyRoute = vi.fn(() => + Promise.resolve( + createLazyRoute('/lazy')({ component: () =>

Lazy component

}), + ), + ) + + const rootRoute = createRootRouteWithContext<{ locale: string }>()({ + beforeLoad: (): { session: Session } => { + calls.push('root.beforeLoad') + return { session: { user: realUser } } + }, + component: () => ( +
+

App shell

+ +
+ ), + }) + + const authedRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authed', + beforeLoad: ({ context }) => { + calls.push('authed.beforeLoad') + if (!context.session.user) { + throw redirect({ to: '/login' }) + } + return { user: context.session.user } + }, + loader: () => { + calls.push('authed.loader') + return { unreadCount: 1 } + }, + component: () => ( +
+

Authed layout

+ +
+ ), + }) + + const postRoute = createRoute({ + getParentRoute: () => authedRoute, + path: '/posts/$postId', + validateSearch: ( + search: { tab?: string } & SearchSchemaInput, + ): { tab: string } => { + if (search.tab === 'broken') { + throw new Error('Unknown tab') + } + return { tab: search.tab ?? 'details' } + }, + context: () => { + calls.push('post.context') + return { scope: 'real scope' } + }, + loader: ({ params }): { post: Post } => { + calls.push('post.loader') + return { post: { id: params.postId, title: 'Real post' } } + }, + component: PostPage, + }) + + function PostPage() { + return ( +
+

Post page

+ +
+ ) + } + + // Reads the state of its own route and of an ancestor through the route + // objects, the way components in route files do. + function PostHeader() { + const { post } = postRoute.useLoaderData() + const { user, locale, scope } = postRoute.useRouteContext() + const { tab } = postRoute.useSearch() + const { unreadCount } = authedRoute.useLoaderData() + + return ( +
+

{post.title}

+

+ {`${user.name} reads post ${post.id} in ${locale} on tab ${tab} with ${unreadCount} unread in ${scope}`} +

+ Sign out +
+ ) + } + + const loginRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/login', + component: () =>

Login page

, + }) + + const lazyRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/lazy', + }).lazy(loadLazyRoute) + + const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: () =>

Home page

, + }) + + const routeTree = rootRoute.addChildren([ + authedRoute.addChildren([postRoute]), + loginRoute, + lazyRoute, + indexRoute, + ]) + + return { + routeTree, + authedRoute, + postRoute, + PostHeader, + calls, + loadLazyRoute, + } +} + +const seededContext = { + locale: 'en', + session: { user: testUser }, + user: testUser, + scope: 'seeded scope', +} + +describe('createTestRouter', () => { + test('runs the lifecycle of the application by default', async () => { + const app = createApp() + + const router = createTestRouter({ + routeTree: app.routeTree, + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'en' }, + }) + render() + + expect( + await screen.findByText( + 'Real user reads post 1 in en on tab details with 1 unread in real scope', + ), + ).toBeInTheDocument() + expect(screen.getByText('App shell')).toBeInTheDocument() + expect(screen.getByText('Authed layout')).toBeInTheDocument() + expect(app.calls).toEqual([ + 'root.beforeLoad', + 'authed.beforeLoad', + 'post.context', + 'authed.loader', + 'post.loader', + ]) + }) + + test('replaces the options a test names and keeps the rest', async () => { + const app = createApp() + + const router = createTestRouter({ + routeTree: app.routeTree, + location: { + to: '/posts/$postId', + params: { postId: '2' }, + search: { tab: 'comments' }, + }, + context: { locale: 'de' }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: testUser } } }, + '/_authed': { loaderData: { unreadCount: 7 } }, + '/_authed/posts/$postId': { + loader: ({ params }) => ({ + post: { id: params.postId, title: 'Replaced post' }, + }), + }, + }, + }) + render() + + expect( + await screen.findByText( + 'Test user reads post 2 in de on tab comments with 7 unread in real scope', + ), + ).toBeInTheDocument() + expect(screen.getByRole('heading')).toHaveTextContent('Replaced post') + // The seed for the root route replaced its beforeLoad. The beforeLoad of + // `/_authed` was not named, so the real one derived the user. + expect(app.calls).toEqual(['authed.beforeLoad', 'post.context']) + }) + + test('replaces beforeLoad, the context option and components', async () => { + const app = createApp() + + const router = createTestRouter({ + routeTree: app.routeTree, + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'en' }, + overrides: { + '/_authed': { + beforeLoad: ({ context }) => ({ + user: { id: 'derived', name: `Derived in ${context.locale}` }, + }), + component: () => , + }, + '/_authed/posts/$postId': { + context: () => ({ scope: 'test scope' }), + component: () => { + const context = app.postRoute.useRouteContext() + return

{`${context.user.name} with ${context.scope}`}

+ }, + }, + }, + }) + render() + + expect( + await screen.findByText('Derived in en with test scope'), + ).toBeInTheDocument() + expect(screen.getByText('App shell')).toBeInTheDocument() + expect(screen.queryByText('Authed layout')).not.toBeInTheDocument() + expect(app.calls).toEqual([ + 'root.beforeLoad', + 'authed.loader', + 'post.loader', + ]) + }) + + test('removes an option that is overridden with undefined', async () => { + const app = createApp() + + const router = createTestRouter({ + routeTree: app.routeTree, + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'en' }, + overrides: { '/_authed': { loader: undefined } }, + }) + await router.load() + + expect(app.calls).not.toContain('authed.loader') + expect( + router.state.matches.find((match) => match.routeId === '/_authed') + ?.loaderData, + ).toBeUndefined() + }) + + test('keeps overrides out of the route tree and out of the next router', async () => { + const app = createApp() + const originalLoader = app.postRoute.options.loader + + const first = createTestRouter({ + routeTree: app.routeTree, + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'en' }, + overrides: { + '/_authed/posts/$postId': { + loaderData: { post: { id: '1', title: 'Seeded post' } }, + }, + }, + }) + await first.load() + expect(first.state.matches.at(-1)?.loaderData).toEqual({ + post: { id: '1', title: 'Seeded post' }, + }) + expect(app.postRoute.options.loader).toBe(originalLoader) + + const second = createTestRouter({ + routeTree: app.routeTree, + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'en' }, + }) + await second.load() + expect(second.state.matches.at(-1)?.loaderData).toEqual({ + post: { id: '1', title: 'Real post' }, + }) + }) + + test('initialises the route objects that application code imports', () => { + const app = createApp() + expect(app.postRoute.id).toBeUndefined() + + createTestRouter({ routeTree: app.routeTree, context: { locale: 'en' } }) + + expect(app.postRoute.id).toBe('/_authed/posts/$postId') + expect(app.postRoute.fullPath).toBe('/posts/$postId') + expect(app.postRoute.to).toBe('/posts/$postId') + expect(app.authedRoute.id).toBe('/_authed') + }) + + test('uses a memory history, or the history it is given', async () => { + const app = createApp() + + const withMemoryHistory = createTestRouter({ + routeTree: app.routeTree, + context: { locale: 'en' }, + }) + expect(withMemoryHistory.history.location.pathname).toBe('/') + expect(window.location.pathname).toBe('/') + + const router = createTestRouter({ + routeTree: app.routeTree, + history: createMemoryHistory({ initialEntries: ['/login'] }), + context: { locale: 'en' }, + }) + render() + + expect(await screen.findByText('Login page')).toBeInTheDocument() + }) + + test('passes the other options to the router', async () => { + const app = createApp() + + const router = createTestRouter({ + routeTree: app.routeTree, + context: { locale: 'en' }, + location: { to: '/login' }, + Wrap: ({ children }) => ( +
{children}
+ ), + }) + render() + + expect(await screen.findByLabelText('Providers')).toHaveTextContent( + 'Login page', + ) + }) + + test('lets an override win over the options of a lazy route', async () => { + const app = createApp() + + const real = createTestRouter({ + routeTree: app.routeTree, + location: { to: '/lazy' }, + context: { locale: 'en' }, + }) + const { unmount } = render() + expect(await screen.findByText('Lazy component')).toBeInTheDocument() + unmount() + + const overridden = createTestRouter({ + routeTree: app.routeTree, + location: { to: '/lazy' }, + context: { locale: 'en' }, + overrides: { '/lazy': { component: () =>

Test component

} }, + }) + render() + expect(await screen.findByText('Test component')).toBeInTheDocument() + expect(screen.queryByText('Lazy component')).not.toBeInTheDocument() + }) + + test('rejects an override for a route that does not exist', () => { + const app = createApp() + + expect(() => + createTestRouter({ + routeTree: app.routeTree, + context: { locale: 'en' }, + // @ts-expect-error not a route id of this tree + overrides: { '/missing': { component: () => null } }, + }), + ).toThrow('The route "/missing" does not exist in the route tree') + }) + + test('rejects conflicting overrides', () => { + const app = createApp() + + expect(() => + createTestRouter({ + routeTree: app.routeTree, + context: { locale: 'en' }, + overrides: { + '/_authed': { + loader: () => ({ unreadCount: 1 }), + loaderData: { unreadCount: 2 }, + }, + }, + }), + ).toThrow('has both "loader" and "loaderData"') + + expect(() => + createTestRouter({ + routeTree: app.routeTree, + context: { locale: 'en' }, + overrides: { + '/_authed': { + beforeLoad: () => ({ user: testUser }), + routeContext: { user: testUser }, + }, + }, + }), + ).toThrow('has both "beforeLoad" and "routeContext"') + }) +}) + +describe('createIsolatedTestRouter', () => { + test('renders one element in one route with the state the test supplies', async () => { + const app = createApp() + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: '5' }, + search: { tab: 'comments' }, + context: seededContext, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } }, + }, + }) + render() + + // The router has loaded, so the first render is complete. + expect(screen.getByRole('heading')).toHaveTextContent('Seeded post') + expect( + screen.getByText( + 'Test user reads post 5 in en on tab comments with 4 unread in seeded scope', + ), + ).toBeInTheDocument() + expect(router.state.location.pathname).toBe('/posts/5') + + // Nothing of the application ran or rendered. + expect(app.calls).toEqual([]) + expect(screen.queryByText('App shell')).not.toBeInTheDocument() + expect(screen.queryByText('Authed layout')).not.toBeInTheDocument() + expect(screen.queryByText('Post page')).not.toBeInTheDocument() + }) + + test('sends search params through validateSearch', async () => { + const app = createApp() + const state = { + routeTree: app.routeTree, + route: '/_authed/posts/$postId', + params: { postId: '5' }, + context: seededContext, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } }, + }, + } as const + + const router = await createIsolatedTestRouter({ + ...state, + element: , + }) + render() + expect(screen.getByText(/on tab details/)).toBeInTheDocument() + + await expect( + createIsolatedTestRouter({ + ...state, + element: , + search: { tab: 'broken' }, + }), + ).rejects.toThrow('Unknown tab') + }) + + test('navigates with the real router and renders no other route', async () => { + const app = createApp() + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: '5' }, + context: seededContext, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } }, + }, + }) + render() + + fireEvent.click(screen.getByRole('link', { name: 'Sign out' })) + + await waitFor(() => { + expect(router.state.location.pathname).toBe('/login') + }) + expect(screen.queryByText('Login page')).not.toBeInTheDocument() + expect(app.calls).toEqual([]) + }) + + test('does not load lazy routes', async () => { + const app = createApp() + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/lazy', + element:

In the lazy route

, + context: { locale: 'en', session: { user: null } }, + }) + render() + + expect(screen.getByText('In the lazy route')).toBeInTheDocument() + expect(app.loadLazyRoute).not.toHaveBeenCalled() + }) + + test('passes the other options to the router, except the default components', async () => { + const app = createApp() + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/login', + element:

Element

, + context: { locale: 'en', session: { user: null } }, + Wrap: ({ children }) => ( +
{children}
+ ), + defaultComponent: () =>

Default component

, + }) + render() + + expect(screen.getByLabelText('Providers')).toHaveTextContent('Element') + expect(screen.queryByText('Default component')).not.toBeInTheDocument() + }) + + test('renders no not-found component of the app after a navigation', async () => { + const app = createApp() + // The router warns that no not-found component is configured. + const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/login', + element:

Element

, + context: { locale: 'en', session: { user: null } }, + defaultNotFoundComponent: () =>

App not found

, + }) + render() + + router.history.push('/missing') + + expect(await screen.findByText('Not Found')).toBeInTheDocument() + expect(screen.queryByText('App not found')).not.toBeInTheDocument() + consoleWarn.mockRestore() + }) + + test('lets an error of the element reach the test', async () => { + const app = createApp() + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + function Broken(): never { + throw new Error('The element is broken') + } + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/login', + element: , + context: { locale: 'en', session: { user: null } }, + }) + + expect(() => render()).toThrow( + 'The element is broken', + ) + consoleError.mockRestore() + }) + + test('fails when a path param is missing', async () => { + const app = createApp() + + await expect( + createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/_authed/posts/$postId', + element: , + // @ts-expect-error `postId` is missing + params: {}, + context: seededContext, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { + post: { id: '5', title: 'Seeded post' }, + }, + }, + }), + ).rejects.toThrow( + 'Missing path params for route "/_authed/posts/$postId": postId.', + ) + }) + + test('fails when the path of the route does not lead to it', async () => { + const app = createApp() + + await expect( + createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/_authed', + element:

Element

, + context: { locale: 'en', session: { user: testUser }, user: testUser }, + loaderData: { '/_authed': { unreadCount: 4 } }, + }), + ).rejects.toThrow('The route "/_authed" is not matched at "/"') + }) + + test('fails for a route that does not exist', async () => { + const app = createApp() + + await expect( + createIsolatedTestRouter({ + routeTree: app.routeTree, + // @ts-expect-error not a route id of this tree + route: '/missing', + element:

Element

, + }), + ).rejects.toThrow('The route "/missing" does not exist in the route tree') + }) +}) diff --git a/packages/react-router/vite.config.ts b/packages/react-router/vite.config.ts index 798d9b74e4..7d82212668 100644 --- a/packages/react-router/vite.config.ts +++ b/packages/react-router/vite.config.ts @@ -32,6 +32,7 @@ export default mergeConfig( './src/index.dev.tsx', './src/ssr/client.ts', './src/ssr/server.ts', + './src/testing.ts', ], srcDir: './src', }), diff --git a/packages/router-core/package.json b/packages/router-core/package.json index ed2b794278..122457db0a 100644 --- a/packages/router-core/package.json +++ b/packages/router-core/package.json @@ -68,6 +68,16 @@ "default": "./dist/cjs/ssr/client.cjs" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing/index.d.ts", + "default": "./dist/esm/testing/index.js" + }, + "require": { + "types": "./dist/cjs/testing/index.d.cts", + "default": "./dist/cjs/testing/index.cjs" + } + }, "./isServer": { "development": { "import": { diff --git a/packages/router-core/src/testing/index.ts b/packages/router-core/src/testing/index.ts new file mode 100644 index 0000000000..00d944b254 --- /dev/null +++ b/packages/router-core/src/testing/index.ts @@ -0,0 +1,30 @@ +export { createIsolatedTestRouterWith, createTestRouterWith } from './router' +export type { + AnyIsolatedTestRouterOptions, + AnyTestRouterOptions, + TestRouterFactory, +} from './router' +export { + assertIsolatedRouteLoaded, + assertRouteTestParams, + createIsolatedRouteTree, + createTestRouteTree, + initRouteTree, + setTestRouterLocation, +} from './routeTree' +export type { + AnyRouteTestOverride, + AnyRouteTestOverrides, + IsolatedRouteTreeOptions, +} from './routeTree' +export type { + IsolatedRouteState, + IsolatedTestRouterOptions, + RouteTestBeforeLoadFn, + RouteTestComponents, + RouteTestContextFn, + RouteTestLoaderFn, + RouteTestOverride, + RouteTestOverrides, + TestRouterOptions, +} from './types' diff --git a/packages/router-core/src/testing/routeTree.ts b/packages/router-core/src/testing/routeTree.ts new file mode 100644 index 0000000000..0f4de1092d --- /dev/null +++ b/packages/router-core/src/testing/routeTree.ts @@ -0,0 +1,344 @@ +import { SEGMENT_TYPE_PARAM } from '../new-process-route-tree' +import { isNotFound } from '../not-found' +import type { AnyRoute } from '../route' +import type { AnyRouter } from '../router' + +type RouteOptionsPatch = Record + +/** + * The untyped shape of a per-route override. The typed shape that tests use + * is `RouteTestOverride` in `./types`. + */ +export interface AnyRouteTestOverride { + beforeLoad?: unknown + loader?: unknown + context?: unknown + loaderData?: unknown + routeContext?: unknown + component?: unknown + pendingComponent?: unknown + errorComponent?: unknown + notFoundComponent?: unknown +} + +export type AnyRouteTestOverrides = Record< + string, + AnyRouteTestOverride | undefined +> + +/** Override keys that replace the route option of the same name. */ +const replacedOptions = [ + 'beforeLoad', + 'loader', + 'context', + 'component', + 'pendingComponent', + 'errorComponent', + 'notFoundComponent', +] as const + +/** + * Everything an isolated route test removes from every route: the options + * that do work, the options that render, and the options that react to the + * lifecycle. The options derived from the URL (`params`, `validateSearch`, + * `search`, `loaderDeps`) stay. + */ +const isolatedRouteOptions: RouteOptionsPatch = { + beforeLoad: undefined, + context: undefined, + loader: undefined, + component: undefined, + pendingComponent: undefined, + errorComponent: undefined, + notFoundComponent: undefined, + shellComponent: undefined, + head: undefined, + scripts: undefined, + headers: undefined, + onEnter: undefined, + onStay: undefined, + onLeave: undefined, + onError: undefined, + onCatch: undefined, +} + +function getChildren(route: AnyRoute): Array | undefined { + return route.children as Array | undefined +} + +/** + * Gives every route of a tree its `id`, `path`, `fullPath` and `to`. + * + * A router does this for the tree it is built from, every time one is + * created. A test router is built from a copy of the tree, so without this + * step the route objects that application code imports would never be + * initialised: `Route.to` would be `undefined` and `Route.useLoaderData()` + * would fall back to the nearest match. + */ +export function initRouteTree(routeTree: AnyRoute): void { + let index = 0 + const visit = (route: AnyRoute) => { + route.init(index++) + getChildren(route)?.forEach(visit) + } + visit(routeTree) +} + +function cloneRouteTree( + routeTree: TRouteTree, + getPatch: (route: AnyRoute) => RouteOptionsPatch | undefined, + keepLazyRoutes: boolean, +): TRouteTree { + const cloneRoute = (route: AnyRoute, parent?: AnyRoute): AnyRoute => { + const patch = getPatch(route) + // Route classes take all their state from `options`, so a fresh instance + // of the same class with copied options is an independent route. + const clone = new (route.constructor as new () => AnyRoute)() + clone.options = { ...route.options, ...patch } + if (parent) { + clone.options.getParentRoute = () => parent + } + clone.isRoot = route.isRoot + + const lazyFn = route.lazyFn + if (lazyFn && keepLazyRoutes) { + // Lazy options are assigned onto the route when they arrive. The test's + // own options have to win over them. + clone.lazyFn = patch + ? () => + lazyFn().then( + (lazyRoute) => + ({ + options: { ...lazyRoute.options, ...patch }, + }) as typeof lazyRoute, + ) + : lazyFn + } + + const children = getChildren(route) + if (children) { + clone.addChildren(children.map((child) => cloneRoute(child, clone))) + } + return clone + } + + return cloneRoute(routeTree) as TRouteTree +} + +function collectRouteIds(routeTree: AnyRoute, ids = new Set()) { + ids.add(routeTree.id) + getChildren(routeTree)?.forEach((child) => collectRouteIds(child, ids)) + return ids +} + +function assertKnownRouteIds(routeTree: AnyRoute, ids: Iterable) { + let known: Set | undefined + for (const id of ids) { + known ??= collectRouteIds(routeTree) + if (!known.has(id)) { + throw new Error( + `The route "${id}" does not exist in the route tree. Known route ids: ${[...known].join(', ')}`, + ) + } + } +} + +function applyOverride( + routeId: string, + override: AnyRouteTestOverride, +): RouteOptionsPatch { + const conflict = + 'loader' in override && 'loaderData' in override + ? ['loader', 'loaderData'] + : 'routeContext' in override && 'context' in override + ? ['context', 'routeContext'] + : 'routeContext' in override && 'beforeLoad' in override + ? ['beforeLoad', 'routeContext'] + : undefined + if (conflict) { + throw new Error( + `The override for route "${routeId}" has both "${conflict[0]}" and "${conflict[1]}". Pass one of them.`, + ) + } + if ( + override.context !== undefined && + typeof override.context !== 'function' + ) { + throw new Error( + `The override for route "${routeId}" passes a value as "context", which replaces the route's \`context\` option and has to be a function. To seed what the route adds to the context, use "routeContext".`, + ) + } + + const patch: RouteOptionsPatch = {} + for (const key of replacedOptions) { + if (key in override) { + patch[key] = override[key] + } + } + if ('loaderData' in override) { + const loaderData = override.loaderData + patch.loader = () => loaderData + } + if ('routeContext' in override) { + // The seed stands for everything the route adds to the context, so + // neither of the two options that produce it may run. + const routeContext = override.routeContext + patch.context = () => routeContext + patch.beforeLoad = undefined + } + return patch +} + +/** + * Copies a route tree for one test router and applies per-route overrides. + * Routes without an override keep the application's options. + */ +export function createTestRouteTree( + routeTree: TRouteTree, + overrides?: AnyRouteTestOverrides, +): TRouteTree { + initRouteTree(routeTree) + if (overrides) { + assertKnownRouteIds(routeTree, Object.keys(overrides)) + } + + return cloneRouteTree( + routeTree, + (route) => { + const override = overrides?.[route.id] + return override ? applyOverride(route.id, override) : undefined + }, + true, + ) +} + +export interface IsolatedRouteTreeOptions { + /** The route the element under test is rendered in. */ + routeId: string + /** The component that renders the element under test. */ + component: unknown + /** Loader data by route id. A route that is not listed has no loader. */ + loaderData: ReadonlyMap +} + +/** + * Copies a route tree for an isolated route test. No route keeps an option + * that does work or renders. The target route renders `component`, and the + * listed routes get a loader that returns the given data. + */ +export function createIsolatedRouteTree( + routeTree: TRouteTree, + options: IsolatedRouteTreeOptions, +): TRouteTree { + initRouteTree(routeTree) + assertKnownRouteIds(routeTree, [ + options.routeId, + ...options.loaderData.keys(), + ]) + + return cloneRouteTree( + routeTree, + (route) => { + const patch = { ...isolatedRouteOptions } + if (options.loaderData.has(route.id)) { + const loaderData = options.loaderData.get(route.id) + patch.loader = () => loaderData + } + if (route.id === options.routeId) { + patch.component = options.component + } + return patch + }, + false, + ) +} + +/** + * Moves a router that has not loaded yet to a location given as navigation + * options (`to`, `params`, `search`, `hash`, `state`). + */ +export function setTestRouterLocation( + router: AnyRouter, + location: object, +): void { + const next = router.buildLocation(location as never) + router.history.replace(next.publicHref, next.state) + router.updateLatestLocation() +} + +/** + * Throws when navigation options for `routeId` leave a required path param + * out. Without this the param would be written into the URL as "undefined". + */ +export function assertRouteTestParams( + router: AnyRouter, + routeId: string, + params: Record | undefined, +): void { + const route = (router.routesById as Record)[routeId]! + const missing: Array = [] + for (const segment of route._interpolation ?? []) { + if ( + typeof segment !== 'string' && + segment[0] === SEGMENT_TYPE_PARAM && + params?.[segment[1]] == null + ) { + missing.push(segment[1]) + } + } + if (missing.length) { + throw new Error( + `Missing path params for route "${routeId}": ${missing.join(', ')}.`, + ) + } +} + +/** + * Throws when an isolated route test did not end up where the test asked: a + * route threw `notFound()` or failed to load, for example because the search + * params did not pass its `validateSearch`, or the target route is not + * matched. + */ +export function assertIsolatedRouteLoaded( + router: AnyRouter, + routeId: string, +): void { + const matches = router.state.matches + const href = router.state.location.href + + for (const match of matches) { + if (match.status === 'notFound') { + const step = isNotFound(match.paramsError) + ? ' while parsing its path params' + : '' + throw new Error( + `The route "${match.routeId}" threw notFound()${step} at "${href}".`, + { cause: match.error }, + ) + } + if (match.status === 'error') { + // A `notFound()` from `validateSearch` arrives wrapped in a + // `SearchParamError` without a message, and the match fails. + if (isNotFound((match.searchError as Error | undefined)?.cause)) { + throw new Error( + `The route "${match.routeId}" threw notFound() while validating its search params at "${href}".`, + { cause: match.error }, + ) + } + throw match.error instanceof Error + ? match.error + : new Error( + `The route "${match.routeId}" failed to load at "${href}": ${String(match.error)}`, + ) + } + } + + const matched = matches.some( + (match) => match.routeId === routeId && match.status === 'success', + ) + if (!matched) { + throw new Error( + `The route "${routeId}" is not matched at "${href}". Matched routes: ${matches.map((match) => match.routeId).join(', ') || 'none'}. Pass the id of a route that its own path leads to; a layout route is reached through one of its child routes.`, + ) + } +} diff --git a/packages/router-core/src/testing/router.ts b/packages/router-core/src/testing/router.ts new file mode 100644 index 0000000000..f416914c0e --- /dev/null +++ b/packages/router-core/src/testing/router.ts @@ -0,0 +1,129 @@ +import { createMemoryHistory } from '@tanstack/history' +import { + assertIsolatedRouteLoaded, + assertRouteTestParams, + createIsolatedRouteTree, + createTestRouteTree, + setTestRouterLocation, +} from './routeTree' +import type { RouterHistory } from '@tanstack/history' +import type { AnyRoute } from '../route' +import type { AnyRouter } from '../router' +import type { AnyRouteTestOverrides } from './routeTree' + +/** A framework's `createRouter`. */ +export type TestRouterFactory = ( + options: any, +) => TRouter + +/** The untyped options of `createTestRouterWith`. */ +export interface AnyTestRouterOptions { + routeTree: AnyRoute + location?: object + overrides?: AnyRouteTestOverrides + history?: RouterHistory + [option: string]: unknown +} + +/** The untyped options of `createIsolatedTestRouterWith`. */ +export interface AnyIsolatedTestRouterOptions { + routeTree: AnyRoute + /** The framework component that renders the element under test. */ + component: unknown + route: string + params?: Record + search?: Record + context?: Record + loaderData?: Record + [option: string]: unknown +} + +function assertNoNotFoundRoute(notFoundRoute: unknown): void { + if (notFoundRoute !== undefined) { + throw new Error( + 'Test routers do not support the deprecated "notFoundRoute" option. Give the root route a "notFoundComponent" instead.', + ) + } +} + +/** + * The framework-independent part of `createTestRouter`. Framework packages + * call it with their own `createRouter` and declare the typed signature. + * + * Creates a router over a copy of the route tree with the overrides applied. + * The router uses a memory history unless `history` is given, and starts at + * `location`. It has not loaded yet. + */ +export function createTestRouterWith( + createRouter: TestRouterFactory, + options: AnyTestRouterOptions, +): TRouter { + assertNoNotFoundRoute(options.notFoundRoute) + const { routeTree, location, overrides, history, ...routerOptions } = options + const router = createRouter({ + ...routerOptions, + routeTree: createTestRouteTree(routeTree, overrides), + history: history ?? createMemoryHistory(), + }) + + if (location) { + setTestRouterLocation(router, location) + } + + return router +} + +/** + * The framework-independent part of `createIsolatedTestRouter`. Framework + * packages call it with their own `createRouter`, turn the element under test + * into `component`, and declare the typed signature. + * + * Creates a router in which no route option that does work or renders + * remains, renders `component` in the route `route`, and resolves once the + * router has loaded at that route's location. + */ +export async function createIsolatedTestRouterWith( + createRouter: TestRouterFactory, + options: AnyIsolatedTestRouterOptions, +): Promise { + assertNoNotFoundRoute(options.notFoundRoute) + const { + routeTree, + component, + route, + params, + search, + context, + loaderData, + ...routerOptions + } = options + + const router = createRouter({ + ...routerOptions, + // Nothing of the application renders around the element, and the router + // does not catch an error that the element throws. + defaultComponent: undefined, + defaultErrorComponent: undefined, + defaultPendingComponent: undefined, + defaultNotFoundComponent: undefined, + disableGlobalCatchBoundary: true, + routeTree: createIsolatedRouteTree(routeTree, { + routeId: route, + component, + loaderData: new Map(Object.entries(loaderData ?? {})), + }), + history: createMemoryHistory(), + context, + }) + + assertRouteTestParams(router, route, params) + setTestRouterLocation(router, { + to: (router.routesById as Record)[route]!.fullPath, + params, + search, + }) + await router.load() + assertIsolatedRouteLoaded(router, route) + + return router +} diff --git a/packages/router-core/src/testing/types.ts b/packages/router-core/src/testing/types.ts new file mode 100644 index 0000000000..72711605c2 --- /dev/null +++ b/packages/router-core/src/testing/types.ts @@ -0,0 +1,271 @@ +import type { RouterHistory } from '@tanstack/history' +import type { + AnyRoute, + BeforeLoadContextOptions, + ContextAsyncReturnType, + ContextReturnType, + LoaderFnContext, + RouteContextOptions, +} from '../route' +import type { RouteById, RouteIds } from '../routeInfo' +import type { + RouterConstructorOptions, + RouterCore, + RouterOptions, + TrailingSlashOption, +} from '../router' +import type { ValidateNavigateOptions } from '../typePrimitives' +import type { Awaitable, ConstrainLiteral } from '../utils' + +/** + * The component options a test can replace on a route. Framework packages + * pass their own component types. + */ +export interface RouteTestComponents { + component?: unknown + pendingComponent?: unknown + errorComponent?: unknown + notFoundComponent?: unknown +} + +/** `true` when a value of this type holds nothing a test has to supply. */ +type IsEmpty = [TValue] extends [void | undefined | null] + ? true + : {} extends TValue + ? true + : false + +type OrVoid = IsEmpty extends true ? TValue | void : TValue + +type OptionalWhenEmpty = + IsEmpty extends true + ? { [K in TKey]?: TValue } + : { [K in TKey]: TValue } + +/** + * A replacement for a route's `beforeLoad`. It receives what the route's own + * `beforeLoad` receives and has to return what that one returns. + */ +export type RouteTestBeforeLoadFn = ( + ctx: BeforeLoadContextOptions< + any, + TRoute['types']['parentRoute'], + TRoute['types']['searchValidator'], + TRoute['types']['params'], + TRoute['types']['routerContext'], + TRoute['types']['routeContextFn'], + TRoute['types']['id'], + any, + any + >, +) => Awaitable>> + +/** + * A replacement for a route's `loader`. It receives what the route's own + * loader receives and has to return the route's loader data. + */ +export type RouteTestLoaderFn = ( + ctx: LoaderFnContext< + any, + TRoute['types']['parentRoute'], + TRoute['types']['id'], + TRoute['types']['params'], + TRoute['types']['loaderDeps'], + TRoute['types']['routerContext'], + TRoute['types']['routeContextFn'], + TRoute['types']['beforeLoadFn'], + any, + any + >, +) => Awaitable< + | TRoute['types']['loaderData'] + | (undefined extends TRoute['types']['loaderData'] ? void : never) +> + +/** A replacement for a route's `context` option. */ +export type RouteTestContextFn = ( + ctx: RouteContextOptions< + TRoute['types']['parentRoute'], + TRoute['types']['params'], + TRoute['types']['routerContext'], + TRoute['types']['loaderDeps'], + TRoute['types']['id'] + >, +) => OrVoid> + +/** + * What a test can replace on one route. Everything is typed from the route. + * + * - `beforeLoad`, `loader`, `context`: replace the route option of the same + * name. Each takes a function with the signature of the original. + * - `loaderData`: a seed for the route's loader data. The route's loader does + * not run. + * - `routeContext`: a seed for everything the route adds to the context. + * Neither the route's `context` option nor its `beforeLoad` runs. + * - The component options replace what the route renders. + * + * The options derived from the URL (`params`, `validateSearch`, `loaderDeps`) + * cannot be replaced. + */ +export type RouteTestOverride< + TRoute extends AnyRoute, + TComponents = RouteTestComponents, +> = TComponents & { + beforeLoad?: RouteTestBeforeLoadFn + loader?: RouteTestLoaderFn + context?: RouteTestContextFn + loaderData?: TRoute['types']['loaderData'] + routeContext?: TRoute['types']['routeContext'] +} + +/** + * Overrides by route id. The root route's id is `rootRouteId`, used as a + * computed key: `{ [rootRouteId]: { ... } }`. + */ +export type RouteTestOverrides< + TRouteTree extends AnyRoute, + TComponents = RouteTestComponents, +> = { + [TId in RouteIds]?: RouteTestOverride< + RouteById, + TComponents + > +} + +type AncestorRoutes = TRoute extends { + types: { parentRoute: infer TParentRoute } +} + ? // The parent of a root route is `any`. + unknown extends TParentRoute + ? never + : TParentRoute extends AnyRoute + ? TParentRoute | AncestorRoutes + : never + : never + +type BranchRoutes = TRoute | AncestorRoutes + +type HasLoaderData = + undefined extends TRoute['types']['loaderData'] ? false : true + +/** + * Loader data by route id for a route and the routes above it. A route whose + * loader returns data needs an entry. + */ +type BranchLoaderData = { + [TBranchRoute in BranchRoutes as HasLoaderData extends true + ? TBranchRoute['types']['id'] + : never]: TBranchRoute['types']['loaderData'] +} & { + [TBranchRoute in BranchRoutes as HasLoaderData extends true + ? never + : TBranchRoute['types']['id']]?: TBranchRoute['types']['loaderData'] +} + +type IsolatedRouteStateFor = OptionalWhenEmpty< + 'params', + TRoute['types']['allParams'] +> & + OptionalWhenEmpty<'search', TRoute['types']['fullSearchSchemaInput']> & + OptionalWhenEmpty<'context', TRoute['types']['allContext']> & + OptionalWhenEmpty<'loaderData', BranchLoaderData> + +/** + * The state an isolated route test supplies for the route `TId`. No route + * option that does work runs in such a test, so the types ask for what those + * options would have produced: + * + * - `params`: all path params of the route. + * - `search`: search params, which still go through `validateSearch`. + * - `context`: the whole context of the route. + * - `loaderData`: loader data by route id, for the route and the routes above + * it whose loader returns data. + */ +export type IsolatedRouteState< + TRouteTree extends AnyRoute, + TId extends RouteIds, +> = { + route: TId +} & IsolatedRouteStateFor> + +/** + * The options of `createTestRouter`: those of `createRouter`, plus the route + * tree, a start location and per-route overrides. Framework packages pass + * their component types as `TComponents`. + */ +export type TestRouterOptions< + TRouteTree extends AnyRoute, + TLocation = unknown, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, + TRouterHistory extends RouterHistory = RouterHistory, + TDehydrated extends Record = Record, + TComponents = RouteTestComponents, +> = RouterConstructorOptions< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated +> & { + routeTree: TRouteTree + /** + * Where the router starts, typed like the options of `navigate`. It + * replaces the current entry of `history`. Without it, the router starts + * at the current location of `history`: `/` for the default memory history. + */ + location?: ValidateNavigateOptions< + RouterCore< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated + >, + TLocation + > + /** + * Per-route overrides. A route that is not listed keeps the application's + * options. + */ + overrides?: RouteTestOverrides + /** + * Not supported: the option is deprecated. Give the root route a + * `notFoundComponent` instead. + */ + notFoundRoute?: never +} + +/** + * The options of `createIsolatedTestRouter`. Framework packages pass the type + * of the element under test as `TElement`. + */ +export type IsolatedTestRouterOptions< + TRouteTree extends AnyRoute, + TId, + TElement, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, +> = Omit< + RouterOptions< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + RouterHistory, + Record + >, + // `search` is the route's search params here, not the router option. + 'routeTree' | 'history' | 'context' | 'search' +> & { + routeTree: TRouteTree + /** The element under test. It renders in place of the route's component. */ + element: TElement + /** + * Not supported: the option is deprecated. Give the root route a + * `notFoundComponent` instead. + */ + notFoundRoute?: never + // Checked here rather than in a constraint on `TId`: with a constraint, + // TypeScript widens a constant such as `rootRouteId` while inferring. + route: ConstrainLiteral> +} & IsolatedRouteStateFor> diff --git a/packages/router-core/tests/testing.test.ts b/packages/router-core/tests/testing.test.ts new file mode 100644 index 0000000000..6b052a6bc3 --- /dev/null +++ b/packages/router-core/tests/testing.test.ts @@ -0,0 +1,614 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute, notFound } from '../src' +import { + assertIsolatedRouteLoaded, + assertRouteTestParams, + createIsolatedRouteTree, + createIsolatedTestRouterWith, + createTestRouteTree, + createTestRouterWith, + initRouteTree, + setTestRouterLocation, +} from '../src/testing' +import { createTestRouter } from './routerTestUtils' +import type { AnyRoute } from '../src' + +function createTree() { + const calls: Array = [] + const loadLazyRoute = vi.fn(() => + Promise.resolve({ options: { component: 'lazy component' } } as any), + ) + + const rootRoute = new BaseRootRoute({ + beforeLoad: () => { + calls.push('root.beforeLoad') + return { session: 'real session' } + }, + component: 'root component', + shellComponent: 'root shell', + }) + + const layoutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + id: 'layout', + loader: () => { + calls.push('layout.loader') + return 'real layout data' + }, + component: 'layout component', + }) + + const postRoute = new BaseRoute({ + getParentRoute: () => layoutRoute, + path: '/posts/$postId', + params: { + parse: (params: { postId: string }) => { + if (params.postId === 'missing') { + throw notFound() + } + return params + }, + }, + validateSearch: (search: Record) => { + if (search.tab === 'broken') { + throw new Error('Unknown tab') + } + if (search.tab === 'missing') { + throw notFound() + } + return { tab: (search.tab as string | undefined) ?? 'details' } + }, + context: () => { + calls.push('post.context') + return { scope: 'real scope' } + }, + beforeLoad: () => { + calls.push('post.beforeLoad') + return { permission: 'real permission' } + }, + loader: () => { + calls.push('post.loader') + return 'real post data' + }, + onEnter: () => { + calls.push('post.onEnter') + }, + component: 'post component', + errorComponent: 'post error component', + }) + + const lazyRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/lazy', + }).lazy(loadLazyRoute) + + const indexRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/', + }) + + const routeTree = rootRoute.addChildren([ + layoutRoute.addChildren([postRoute]), + lazyRoute, + indexRoute, + ]) + + return { routeTree, rootRoute, layoutRoute, postRoute, calls, loadLazyRoute } +} + +function createRouter(routeTree: AnyRoute, href: string) { + return createTestRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: [href] }), + context: { locale: 'en' }, + }) +} + +function getMatch(router: ReturnType, routeId: string) { + return router.state.matches.find((match) => match.routeId === routeId) +} + +describe('initRouteTree', () => { + test('gives every route its id and paths without a router', () => { + const { routeTree, layoutRoute, postRoute } = createTree() + expect(postRoute.id).toBeUndefined() + + initRouteTree(routeTree) + + expect(routeTree.id).toBe('__root__') + expect(layoutRoute.id).toBe('/layout') + expect(postRoute.id).toBe('/layout/posts/$postId') + expect(postRoute.fullPath).toBe('/posts/$postId') + expect(postRoute.to).toBe('/posts/$postId') + expect(postRoute.parentRoute).toBe(layoutRoute) + }) + + test('initialises routes added to a tree that a router has processed', () => { + const { routeTree, rootRoute } = createTree() + createRouter(routeTree, '/') + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + rootRoute.addChildren([ + ...(rootRoute.children as Array), + aboutRoute, + ]) + + expect(() => + createTestRouteTree(routeTree, { + '/about': { loaderData: 'seeded about data' }, + }), + ).not.toThrow() + expect(aboutRoute.id).toBe('/about') + expect(aboutRoute.to).toBe('/about') + }) +}) + +describe('createTestRouteTree', () => { + test('copies every route and leaves the original tree untouched', async () => { + const { routeTree, postRoute, calls } = createTree() + const originalOptions = { ...postRoute.options } + + const testTree = createTestRouteTree(routeTree, { + '/layout/posts/$postId': { loaderData: 'seeded post data' }, + }) + const router = createRouter(testTree, '/posts/1') + await router.load() + + const testPostRoute = router.routesById['/layout/posts/$postId']! + expect(testPostRoute).not.toBe(postRoute) + expect(testPostRoute).toBeInstanceOf(BaseRoute) + expect(testPostRoute.parentRoute).toBe(router.routesById['/layout']) + expect(testPostRoute.parentRoute).not.toBe(postRoute.parentRoute) + expect(router.routesById['__root__']).toBeInstanceOf(BaseRootRoute) + expect(postRoute.options).toEqual(originalOptions) + expect(getMatch(router, '/layout/posts/$postId')?.loaderData).toBe( + 'seeded post data', + ) + expect(calls).not.toContain('post.loader') + + // The route objects that application code holds are initialised too. + expect(postRoute.id).toBe('/layout/posts/$postId') + expect(postRoute.to).toBe('/posts/$postId') + }) + + test('runs the options of the application for routes without an override', async () => { + const { routeTree, calls } = createTree() + + const router = createRouter(createTestRouteTree(routeTree), '/posts/1') + await router.load() + + expect(calls).toEqual([ + 'root.beforeLoad', + 'post.context', + 'post.beforeLoad', + 'layout.loader', + 'post.loader', + 'post.onEnter', + ]) + expect(getMatch(router, '/layout/posts/$postId')?.context).toEqual({ + locale: 'en', + session: 'real session', + scope: 'real scope', + permission: 'real permission', + }) + }) + + test('takes routeContext as a seed for everything the route contributes', async () => { + const { routeTree, calls } = createTree() + + const router = createRouter( + createTestRouteTree(routeTree, { + '/layout/posts/$postId': { routeContext: { scope: 'seeded scope' } }, + }), + '/posts/1', + ) + await router.load() + + expect(calls).not.toContain('post.context') + expect(calls).not.toContain('post.beforeLoad') + expect(getMatch(router, '/layout/posts/$postId')?.context).toEqual({ + locale: 'en', + session: 'real session', + scope: 'seeded scope', + }) + }) + + test('replaces the context option, beforeLoad and the loader with functions', async () => { + const { routeTree, calls } = createTree() + const loader = vi.fn(({ params }: { params: { postId: string } }) => { + return `replaced data for ${params.postId}` + }) + + const router = createRouter( + createTestRouteTree(routeTree, { + '/layout/posts/$postId': { + context: () => ({ scope: 'replaced scope' }), + beforeLoad: () => ({ permission: 'replaced permission' }), + loader, + }, + }), + '/posts/7', + ) + await router.load() + + const match = getMatch(router, '/layout/posts/$postId') + expect(match?.context).toEqual({ + locale: 'en', + session: 'real session', + scope: 'replaced scope', + permission: 'replaced permission', + }) + expect(match?.loaderData).toBe('replaced data for 7') + expect(calls).toEqual(['root.beforeLoad', 'layout.loader', 'post.onEnter']) + }) + + test('seeds loader data and replaces components', async () => { + const { routeTree, calls } = createTree() + + const router = createRouter( + createTestRouteTree(routeTree, { + '/layout': { loaderData: 'seeded layout data' }, + '/layout/posts/$postId': { component: 'test component' }, + }), + '/posts/1', + ) + await router.load() + + expect(getMatch(router, '/layout')?.loaderData).toBe('seeded layout data') + expect(calls).not.toContain('layout.loader') + expect(router.routesById['/layout/posts/$postId']!.options.component).toBe( + 'test component', + ) + }) + + test('lets an override win over the options of a lazy route', async () => { + const { routeTree, loadLazyRoute } = createTree() + + const real = createRouter(createTestRouteTree(routeTree), '/lazy') + await real.load() + expect(real.routesById['/lazy']!.options.component).toBe('lazy component') + + const overridden = createRouter( + createTestRouteTree(routeTree, { + '/lazy': { component: 'test component' }, + }), + '/lazy', + ) + await overridden.load() + expect(overridden.routesById['/lazy']!.options.component).toBe( + 'test component', + ) + expect(loadLazyRoute).toHaveBeenCalledTimes(2) + }) + + test('rejects an unknown route id and conflicting overrides', () => { + const { routeTree } = createTree() + + expect(() => createTestRouteTree(routeTree, { '/missing': {} })).toThrow( + 'The route "/missing" does not exist in the route tree. Known route ids: __root__, /layout, /layout/posts/$postId, /lazy, /', + ) + expect(() => + createTestRouteTree(routeTree, { + '/layout': { loader: () => 'a', loaderData: 'b' }, + }), + ).toThrow( + 'The override for route "/layout" has both "loader" and "loaderData". Pass one of them.', + ) + expect(() => + createTestRouteTree(routeTree, { + '/layout': { beforeLoad: () => ({}), routeContext: {} }, + }), + ).toThrow( + 'The override for route "/layout" has both "beforeLoad" and "routeContext". Pass one of them.', + ) + expect(() => + createTestRouteTree(routeTree, { + '/layout': { context: () => ({}), routeContext: {} }, + }), + ).toThrow( + 'The override for route "/layout" has both "context" and "routeContext". Pass one of them.', + ) + }) + + test('rejects a value for the context option', () => { + const { routeTree } = createTree() + + expect(() => + createTestRouteTree(routeTree, { + '/layout': { context: { scope: 'a value' } }, + }), + ).toThrow( + 'The override for route "/layout" passes a value as "context", which replaces the route\'s `context` option and has to be a function. To seed what the route adds to the context, use "routeContext".', + ) + }) +}) + +describe('createIsolatedRouteTree', () => { + test('keeps no option that does work or renders, and seeds the given loader data', async () => { + const { routeTree, calls, loadLazyRoute } = createTree() + + const router = createRouter( + createIsolatedRouteTree(routeTree, { + routeId: '/layout/posts/$postId', + component: 'element under test', + loaderData: new Map([ + ['/layout/posts/$postId', 'seeded post data'], + ['/layout', undefined], + ]), + }), + '/posts/1?tab=comments', + ) + await router.load() + + expect(calls).toEqual([]) + const match = getMatch(router, '/layout/posts/$postId') + expect(match?.status).toBe('success') + expect(match?.loaderData).toBe('seeded post data') + // The router context is the whole context of every match. + expect(match?.context).toEqual({ locale: 'en' }) + // The options derived from the URL still run. + expect(match?.search).toEqual({ tab: 'comments' }) + expect(match?.params).toEqual({ postId: '1' }) + + const routes = router.routesById as Record + expect(routes['/layout/posts/$postId']!.options.component).toBe( + 'element under test', + ) + expect(routes['/layout/posts/$postId']!.options.errorComponent).toBe( + undefined, + ) + expect(routes['/layout']!.options.component).toBe(undefined) + expect(routes['__root__']!.options.component).toBe(undefined) + expect((routes['__root__']!.options as any).shellComponent).toBe(undefined) + + await router.navigate({ to: '/lazy' }) + expect(router.state.location.pathname).toBe('/lazy') + expect(loadLazyRoute).not.toHaveBeenCalled() + }) + + test('rejects an unknown route id', () => { + const { routeTree } = createTree() + + expect(() => + createIsolatedRouteTree(routeTree, { + routeId: '/missing', + component: 'element under test', + loaderData: new Map(), + }), + ).toThrow('The route "/missing" does not exist in the route tree') + }) +}) + +describe('helpers for a test router', () => { + test('setTestRouterLocation moves a router that has not loaded yet', async () => { + const { routeTree } = createTree() + const router = createRouter(createTestRouteTree(routeTree), '/') + + setTestRouterLocation(router, { + to: '/posts/$postId', + params: { postId: '3' }, + search: { tab: 'comments' }, + }) + await router.load() + + expect(router.state.location.href).toBe('/posts/3?tab=comments') + expect(getMatch(router, '/layout/posts/$postId')?.params).toEqual({ + postId: '3', + }) + }) + + test('assertRouteTestParams names the path params that are missing', () => { + const { routeTree } = createTree() + const router = createRouter(createTestRouteTree(routeTree), '/') + + expect(() => + assertRouteTestParams(router, '/layout/posts/$postId', undefined), + ).toThrow('Missing path params for route "/layout/posts/$postId": postId.') + expect(() => + assertRouteTestParams(router, '/layout/posts/$postId', { postId: '1' }), + ).not.toThrow() + expect(() => + assertRouteTestParams(router, '/lazy', undefined), + ).not.toThrow() + }) + + test('assertIsolatedRouteLoaded passes for a matched route', async () => { + const { routeTree } = createTree() + const router = createRouter( + createIsolatedRouteTree(routeTree, { + routeId: '/layout/posts/$postId', + component: 'element under test', + loaderData: new Map(), + }), + '/posts/1', + ) + await router.load() + + expect(() => + assertIsolatedRouteLoaded(router, '/layout/posts/$postId'), + ).not.toThrow() + }) + + test('assertIsolatedRouteLoaded throws the error of a failed match', async () => { + const { routeTree } = createTree() + const router = createRouter( + createIsolatedRouteTree(routeTree, { + routeId: '/layout/posts/$postId', + component: 'element under test', + loaderData: new Map(), + }), + '/posts/1?tab=broken', + ) + await router.load() + + expect(() => + assertIsolatedRouteLoaded(router, '/layout/posts/$postId'), + ).toThrow('Unknown tab') + }) + + test('assertIsolatedRouteLoaded explains a route that is not matched', async () => { + const { routeTree } = createTree() + const router = createRouter( + createIsolatedRouteTree(routeTree, { + routeId: '/layout', + component: 'element under test', + loaderData: new Map(), + }), + '/', + ) + await router.load() + + expect(() => assertIsolatedRouteLoaded(router, '/layout')).toThrow( + 'The route "/layout" is not matched at "/". Matched routes: __root__, /.', + ) + }) +}) + +describe('createTestRouterWith', () => { + const createRouterCore = (options: any) => createTestRouter(options) + + test('creates the router with the given factory, over a copy of the tree', async () => { + const { routeTree, rootRoute, calls } = createTree() + const factory = vi.fn(createRouterCore) + + const router = createTestRouterWith(factory, { + routeTree, + context: { locale: 'en' }, + location: { + to: '/posts/$postId', + params: { postId: '3' }, + search: { tab: 'comments' }, + }, + overrides: { '/layout': { loaderData: 'seeded layout data' } }, + defaultPreloadStaleTime: 5, + }) + await router.load() + + expect(factory).toHaveBeenCalledTimes(1) + expect(router.routeTree).not.toBe(rootRoute) + expect(router.options.defaultPreloadStaleTime).toBe(5) + expect(router.state.location.href).toBe('/posts/3?tab=comments') + expect(getMatch(router, '/layout')?.loaderData).toBe('seeded layout data') + expect(calls).toContain('post.loader') + expect(calls).not.toContain('layout.loader') + }) + + test('uses a memory history unless one is given', () => { + const { routeTree } = createTree() + + const withMemoryHistory = createTestRouterWith(createRouterCore, { + routeTree, + context: { locale: 'en' }, + location: { to: '/lazy' }, + }) + expect(withMemoryHistory.history.location.pathname).toBe('/lazy') + expect(window.location.pathname).toBe('/') + + const history = createMemoryHistory({ initialEntries: ['/posts/1'] }) + const withHistory = createTestRouterWith(createRouterCore, { + routeTree, + history, + context: { locale: 'en' }, + }) + expect(withHistory.history).toBe(history) + expect(withHistory.history.location.pathname).toBe('/posts/1') + }) +}) + +describe('createIsolatedTestRouterWith', () => { + const createRouterCore = (options: any) => createTestRouter(options) + + test('resolves to a loaded router that renders the component in the route', async () => { + const { routeTree, calls } = createTree() + + const router = await createIsolatedTestRouterWith(createRouterCore, { + routeTree, + route: '/layout/posts/$postId', + component: 'element under test', + params: { postId: '4' }, + search: { tab: 'comments' }, + context: { locale: 'en', session: 'seeded session' }, + loaderData: { + '/layout': 'seeded layout data', + '/layout/posts/$postId': 'seeded post data', + }, + defaultComponent: 'default component', + defaultNotFoundComponent: 'default not-found component', + }) + + expect(calls).toEqual([]) + expect(router.state.status).toBe('idle') + expect(router.state.location.href).toBe('/posts/4?tab=comments') + const match = getMatch(router, '/layout/posts/$postId') + expect(match?.status).toBe('success') + expect(match?.loaderData).toBe('seeded post data') + expect(match?.context).toEqual({ locale: 'en', session: 'seeded session' }) + expect(getMatch(router, '/layout')?.loaderData).toBe('seeded layout data') + + const routes = router.routesById as Record + expect(routes['/layout/posts/$postId']!.options.component).toBe( + 'element under test', + ) + // Framework options, so core types do not know them. + const options = router.options as Record + expect(options.defaultComponent).toBeUndefined() + expect(options.defaultNotFoundComponent).toBeUndefined() + expect(router.options.disableGlobalCatchBoundary).toBe(true) + }) + + test('rejects when the route cannot be reached as asked', async () => { + const { routeTree } = createTree() + const base = { routeTree, component: 'element under test' } + + await expect( + createIsolatedTestRouterWith(createRouterCore, { + ...base, + route: '/missing', + }), + ).rejects.toThrow('The route "/missing" does not exist in the route tree') + await expect( + createIsolatedTestRouterWith(createRouterCore, { + ...base, + route: '/layout/posts/$postId', + }), + ).rejects.toThrow( + 'Missing path params for route "/layout/posts/$postId": postId.', + ) + await expect( + createIsolatedTestRouterWith(createRouterCore, { + ...base, + route: '/layout/posts/$postId', + params: { postId: '1' }, + search: { tab: 'broken' }, + }), + ).rejects.toThrow('Unknown tab') + await expect( + createIsolatedTestRouterWith(createRouterCore, { + ...base, + route: '/layout/posts/$postId', + params: { postId: 'missing' }, + }), + ).rejects.toThrow( + 'The route "/layout/posts/$postId" threw notFound() while parsing its path params at "/posts/missing".', + ) + await expect( + createIsolatedTestRouterWith(createRouterCore, { + ...base, + route: '/layout/posts/$postId', + params: { postId: '1' }, + search: { tab: 'missing' }, + }), + ).rejects.toThrow( + 'The route "/layout/posts/$postId" threw notFound() while validating its search params at "/posts/1?tab=missing".', + ) + await expect( + createIsolatedTestRouterWith(createRouterCore, { + ...base, + route: '/layout', + }), + ).rejects.toThrow('The route "/layout" is not matched at "/"') + }) +}) diff --git a/packages/router-core/vite.config.ts b/packages/router-core/vite.config.ts index 97859dda97..c4a3111547 100644 --- a/packages/router-core/vite.config.ts +++ b/packages/router-core/vite.config.ts @@ -44,6 +44,7 @@ export default mergeConfig( './src/index.ts', './src/ssr/client.ts', './src/ssr/server.ts', + './src/testing/index.ts', './src/scroll-restoration-script/client.ts', './src/scroll-restoration-script/server.ts', './src/isServer/server.ts', diff --git a/packages/solid-router/package.json b/packages/solid-router/package.json index 80840069ea..ba989021fe 100644 --- a/packages/solid-router/package.json +++ b/packages/solid-router/package.json @@ -90,6 +90,20 @@ "default": "./dist/cjs/ssr/client.cjs" } }, + "./testing": { + "solid": { + "types": "./dist/source/testing.d.ts", + "default": "./dist/source/testing.js" + }, + "import": { + "types": "./dist/esm/testing.d.ts", + "default": "./dist/esm/testing.js" + }, + "require": { + "types": "./dist/cjs/testing.d.cts", + "default": "./dist/cjs/testing.cjs" + } + }, "./package.json": "./package.json" }, "sideEffects": false, diff --git a/packages/solid-router/src/testing.ts b/packages/solid-router/src/testing.ts new file mode 100644 index 0000000000..5c023a8800 --- /dev/null +++ b/packages/solid-router/src/testing.ts @@ -0,0 +1,165 @@ +import { + createIsolatedTestRouterWith, + createTestRouterWith, +} from '@tanstack/router-core/testing' +import { createRouter } from './router' +import type { JSX } from 'solid-js' +import type { RouterHistory } from '@tanstack/history' +import type { AnyRoute, TrailingSlashOption } from '@tanstack/router-core' +import type { + RouteTestOverrides as CoreRouteTestOverrides, + IsolatedTestRouterOptions, + TestRouterOptions, +} from '@tanstack/router-core/testing' +import type { + ErrorRouteComponent, + NotFoundRouteComponent, + RouteComponent, +} from './route' +import type { Router } from './router' + +export type { + IsolatedRouteState, + RouteTestBeforeLoadFn, + RouteTestContextFn, + RouteTestLoaderFn, +} from '@tanstack/router-core/testing' + +/** The component options a test can replace on a route. */ +export interface RouteTestComponents { + component?: RouteComponent + pendingComponent?: RouteComponent + errorComponent?: false | null | undefined | ErrorRouteComponent + notFoundComponent?: NotFoundRouteComponent +} + +/** + * Overrides by route id, typed from the route tree. The root route's id is + * `rootRouteId`, used as a computed key: `{ [rootRouteId]: { ... } }`. + */ +export type RouteTestOverrides = + CoreRouteTestOverrides + +/** The options of `createTestRouter`: those of `createRouter`, plus `location` and `overrides`. */ +export type CreateTestRouterOptions< + TRouteTree extends AnyRoute, + TLocation = unknown, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, + TRouterHistory extends RouterHistory = RouterHistory, + TDehydrated extends Record = Record, +> = TestRouterOptions< + TRouteTree, + TLocation, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated, + RouteTestComponents +> + +/** + * The options of `createIsolatedTestRouter`. Solid evaluates JSX right away, + * so the element under test is passed as a function: `() => `. + */ +export type CreateIsolatedTestRouterOptions< + TRouteTree extends AnyRoute, + TId, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, +> = IsolatedTestRouterOptions< + TRouteTree, + TId, + () => JSX.Element, + TTrailingSlashOption, + TDefaultStructuralSharingOption +> + +/** + * Creates a router for a test, over a copy of the route tree. It takes the + * options of `createRouter`, plus `location` and `overrides`. Every route runs + * the application's own options unless `overrides` replaces them. Without a + * `history`, the router uses a memory history. + * + * The router has not loaded yet. Render it with `RouterProvider`, or call + * `router.load()` first. + * + * ```tsx + * const router = createTestRouter({ + * routeTree, + * context: { queryClient }, + * location: { to: '/posts/$postId', params: { postId: '1' } }, + * overrides: { '/posts/$postId': { loaderData: { post } } }, + * }) + * render(() => ) + * ``` + */ +export function createTestRouter< + TRouteTree extends AnyRoute, + const TLocation = unknown, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, + TRouterHistory extends RouterHistory = RouterHistory, + TDehydrated extends Record = Record, +>( + options: CreateTestRouterOptions< + TRouteTree, + TLocation, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated + >, +): Router< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated +> { + return createTestRouterWith(createRouter, options as any) as any +} + +/** + * Creates a router that renders one element inside one route, with the state + * the test supplies. It resolves once the router has loaded, so the first + * render of `` is complete. + * + * No `context`, `beforeLoad` or `loader` of any route runs, and no route + * component renders. The options are typed from the route: they ask for the + * context and the loader data those options would have produced. + * + * ```tsx + * const router = await createIsolatedTestRouter({ + * routeTree, + * route: '/posts/$postId', + * element: () => , + * params: { postId: '1' }, + * loaderData: { '/posts/$postId': { post } }, + * }) + * render(() => ) + * ``` + */ +export function createIsolatedTestRouter< + TRouteTree extends AnyRoute, + // `IsolatedTestRouterOptions` checks that `route` is a route id of the tree. + const TId extends string, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, +>( + options: CreateIsolatedTestRouterOptions< + TRouteTree, + TId, + TTrailingSlashOption, + TDefaultStructuralSharingOption + >, +): Promise< + Router +> { + const { element, ...state } = options as any + // The function that creates the element is itself a Solid component. + return createIsolatedTestRouterWith(createRouter, { + ...state, + component: element, + }) as any +} diff --git a/packages/solid-router/tests/testing.test-d.tsx b/packages/solid-router/tests/testing.test-d.tsx new file mode 100644 index 0000000000..7eddaa4114 --- /dev/null +++ b/packages/solid-router/tests/testing.test-d.tsx @@ -0,0 +1,108 @@ +import { describe, expectTypeOf, test } from 'vitest' +import { createRootRouteWithContext, createRoute, rootRouteId } from '../src' +import { createIsolatedTestRouter, createTestRouter } from '../src/testing' +import type { Router } from '../src' +import type { IsolatedRouteState } from '../src/testing' + +interface User { + id: string +} + +const rootRoute = createRootRouteWithContext<{ locale: string }>()({ + beforeLoad: (): { session: { user: User | null } } => ({ + session: { user: null }, + }), +}) + +const authedRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authed', + beforeLoad: ({ context }) => ({ user: context.session.user as User }), + loader: () => ({ unreadCount: 1 }), +}) + +const postRoute = createRoute({ + getParentRoute: () => authedRoute, + path: '/posts/$postId', + loader: ({ params }) => ({ post: { id: params.postId } }), +}) + +const routeTree = rootRoute.addChildren([authedRoute.addChildren([postRoute])]) + +type RouteTree = typeof routeTree + +type RequiredKeys = { + [K in keyof T]-?: {} extends Pick ? never : K +}[keyof T] + +const postState = { + routeTree, + route: '/_authed/posts/$postId', + element: () =>
, + params: { postId: '1' }, + context: { locale: 'en', session: { user: null }, user: { id: '1' } }, + loaderData: { + '/_authed': { unreadCount: 1 }, + '/_authed/posts/$postId': { post: { id: '1' } }, + }, +} as const + +describe('createIsolatedTestRouter', () => { + test('asks for everything the route promises to its components', () => { + type PostState = IsolatedRouteState + + expectTypeOf>().toEqualTypeOf< + 'route' | 'params' | 'context' | 'loaderData' + >() + expectTypeOf>().toEqualTypeOf< + '/_authed' | '/_authed/posts/$postId' + >() + }) + + test('resolves to the Solid router type', () => { + expectTypeOf(createIsolatedTestRouter(postState)).toEqualTypeOf< + Promise> + >() + }) + + test('takes the element as a function, since Solid evaluates JSX right away', () => { + const elementNotFunction = { ...postState, element:
} + // @ts-expect-error the element has to be a function that returns JSX + void createIsolatedTestRouter(elementNotFunction) + }) + + test('rejects state that is incomplete', () => { + const withoutAncestorLoaderData = { + ...postState, + loaderData: { '/_authed/posts/$postId': { post: { id: '1' } } }, + } as const + // @ts-expect-error the loader data of `/_authed` is missing + void createIsolatedTestRouter(withoutAncestorLoaderData) + }) +}) + +describe('createTestRouter', () => { + test('returns the Solid router type and types the overrides', () => { + expectTypeOf( + createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: '1' } }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: { id: '1' } } } }, + '/_authed/posts/$postId': { + loader: ({ params }) => ({ post: { id: params.postId } }), + }, + }, + }), + ).toEqualTypeOf>() + + const wrongSeed = { + routeTree, + context: { locale: 'en' }, + overrides: { '/_authed': { loaderData: { unreadCount: 'many' } } }, + } as const + // @ts-expect-error `unreadCount` is a number + createTestRouter(wrongSeed) + }) +}) diff --git a/packages/solid-router/tests/testing.test.tsx b/packages/solid-router/tests/testing.test.tsx new file mode 100644 index 0000000000..6e86a0a355 --- /dev/null +++ b/packages/solid-router/tests/testing.test.tsx @@ -0,0 +1,234 @@ +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@solidjs/testing-library' +import { afterEach, describe, expect, test } from 'vitest' +import { + Link, + Outlet, + RouterProvider, + createRootRouteWithContext, + createRoute, + redirect, + rootRouteId, +} from '../src' +import { createIsolatedTestRouter, createTestRouter } from '../src/testing' + +afterEach(() => { + cleanup() +}) + +interface User { + id: string + name: string +} + +interface Session { + user: User | null +} + +const realUser: User = { id: 'real', name: 'Real user' } +const testUser: User = { id: 'test', name: 'Test user' } + +function createApp() { + const calls: Array = [] + + const rootRoute = createRootRouteWithContext<{ locale: string }>()({ + beforeLoad: (): { session: Session } => { + calls.push('root.beforeLoad') + return { session: { user: realUser } } + }, + component: () => ( +
+

App shell

+ +
+ ), + }) + + const authedRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authed', + beforeLoad: ({ context }) => { + calls.push('authed.beforeLoad') + if (!context.session.user) { + throw redirect({ to: '/login' }) + } + return { user: context.session.user } + }, + loader: () => { + calls.push('authed.loader') + return { unreadCount: 1 } + }, + component: () => ( +
+

Authed layout

+ +
+ ), + }) + + const postRoute = createRoute({ + getParentRoute: () => authedRoute, + path: '/posts/$postId', + loader: ({ params }) => { + calls.push('post.loader') + return { post: { id: params.postId, title: 'Real post' } } + }, + component: () => , + }) + + // Reads the state of its own route and of an ancestor through the route + // objects, the way components in route files do. + function PostHeader() { + const data = postRoute.useLoaderData() + const context = postRoute.useRouteContext() + const authedData = authedRoute.useLoaderData() + + return ( +
+

{data().post.title}

+

+ {`${context().user.name} reads post ${data().post.id} in ${context().locale} with ${authedData().unreadCount} unread`} +

+ Sign out +
+ ) + } + + const loginRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/login', + component: () =>

Login page

, + }) + + const routeTree = rootRoute.addChildren([ + authedRoute.addChildren([postRoute]), + loginRoute, + ]) + + return { routeTree, PostHeader, calls } +} + +describe('createTestRouter', () => { + test('runs the lifecycle of the application by default', async () => { + const app = createApp() + + const router = createTestRouter({ + routeTree: app.routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: '1' } }, + }) + render(() => ) + + expect( + await screen.findByText('Real user reads post 1 in en with 1 unread'), + ).toBeInTheDocument() + expect(screen.getByText('App shell')).toBeInTheDocument() + expect(app.calls).toEqual([ + 'root.beforeLoad', + 'authed.beforeLoad', + 'authed.loader', + 'post.loader', + ]) + }) + + test('replaces the options a test names and keeps the rest', async () => { + const app = createApp() + + const router = createTestRouter({ + routeTree: app.routeTree, + context: { locale: 'de' }, + location: { to: '/posts/$postId', params: { postId: '2' } }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: testUser } } }, + '/_authed': { loaderData: { unreadCount: 7 } }, + '/_authed/posts/$postId': { + loader: ({ params }) => ({ + post: { id: params.postId, title: 'Replaced post' }, + }), + }, + }, + }) + render(() => ) + + expect( + await screen.findByText('Test user reads post 2 in de with 7 unread'), + ).toBeInTheDocument() + expect(screen.getByRole('heading')).toHaveTextContent('Replaced post') + expect(app.calls).toEqual(['authed.beforeLoad']) + }) +}) + +describe('createIsolatedTestRouter', () => { + test('renders one element in one route with the state the test supplies', async () => { + const app = createApp() + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/_authed/posts/$postId', + element: () => , + params: { postId: '5' }, + context: { locale: 'en', session: { user: testUser }, user: testUser }, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } }, + }, + }) + render(() => ) + + // The router has loaded, so the first render is complete. + expect(screen.getByRole('heading')).toHaveTextContent('Seeded post') + expect( + screen.getByText('Test user reads post 5 in en with 4 unread'), + ).toBeInTheDocument() + expect(app.calls).toEqual([]) + expect(screen.queryByText('App shell')).not.toBeInTheDocument() + expect(screen.queryByText('Authed layout')).not.toBeInTheDocument() + }) + + test('navigates with the real router and renders no other route', async () => { + const app = createApp() + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/_authed/posts/$postId', + element: () => , + params: { postId: '5' }, + context: { locale: 'en', session: { user: testUser }, user: testUser }, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } }, + }, + }) + render(() => ) + + fireEvent.click(screen.getByRole('link', { name: 'Sign out' })) + + await waitFor(() => { + expect(router.state.location.pathname).toBe('/login') + }) + expect(screen.queryByText('Login page')).not.toBeInTheDocument() + expect(app.calls).toEqual([]) + }) + + test('passes the other options to the router', async () => { + const app = createApp() + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/login', + element: () =>

Element

, + context: { locale: 'en', session: { user: null } }, + Wrap: (props) => ( +
{props.children}
+ ), + }) + render(() => ) + + expect(screen.getByLabelText('Providers')).toHaveTextContent('Element') + }) +}) diff --git a/packages/solid-router/vite.config.ts b/packages/solid-router/vite.config.ts index 3c9e49ec37..e562bfc7a9 100644 --- a/packages/solid-router/vite.config.ts +++ b/packages/solid-router/vite.config.ts @@ -59,6 +59,7 @@ export default defineConfig((env) => './src/index.dev.tsx', './src/ssr/client.ts', './src/ssr/server.ts', + './src/testing.ts', ], srcDir: './src', }), diff --git a/packages/vue-router/package.json b/packages/vue-router/package.json index 93ae8fdeed..e7a59e5d13 100644 --- a/packages/vue-router/package.json +++ b/packages/vue-router/package.json @@ -59,6 +59,12 @@ "default": "./dist/esm/ssr/client.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing.d.ts", + "default": "./dist/esm/testing.js" + } + }, "./package.json": "./package.json" }, "sideEffects": false, diff --git a/packages/vue-router/src/testing.ts b/packages/vue-router/src/testing.ts new file mode 100644 index 0000000000..2d9739fb5d --- /dev/null +++ b/packages/vue-router/src/testing.ts @@ -0,0 +1,166 @@ +import { + createIsolatedTestRouterWith, + createTestRouterWith, +} from '@tanstack/router-core/testing' +import { createRouter } from './router' +import type { VNode } from 'vue' +import type { RouterHistory } from '@tanstack/history' +import type { AnyRoute, TrailingSlashOption } from '@tanstack/router-core' +import type { + RouteTestOverrides as CoreRouteTestOverrides, + IsolatedTestRouterOptions, + TestRouterOptions, +} from '@tanstack/router-core/testing' +import type { + ErrorRouteComponent, + NotFoundRouteComponent, + RouteComponent, + VueSFC, +} from './route' +import type { Router } from './router' + +export type { + IsolatedRouteState, + RouteTestBeforeLoadFn, + RouteTestContextFn, + RouteTestLoaderFn, +} from '@tanstack/router-core/testing' + +/** The component options a test can replace on a route. */ +export interface RouteTestComponents { + component?: RouteComponent | VueSFC + pendingComponent?: RouteComponent | VueSFC + errorComponent?: false | null | undefined | ErrorRouteComponent | VueSFC + notFoundComponent?: NotFoundRouteComponent | VueSFC +} + +/** + * Overrides by route id, typed from the route tree. The root route's id is + * `rootRouteId`, used as a computed key: `{ [rootRouteId]: { ... } }`. + */ +export type RouteTestOverrides = + CoreRouteTestOverrides + +/** The options of `createTestRouter`: those of `createRouter`, plus `location` and `overrides`. */ +export type CreateTestRouterOptions< + TRouteTree extends AnyRoute, + TLocation = unknown, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, + TRouterHistory extends RouterHistory = RouterHistory, + TDehydrated extends Record = Record, +> = TestRouterOptions< + TRouteTree, + TLocation, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated, + RouteTestComponents +> + +/** + * The options of `createIsolatedTestRouter`. The element under test is a + * vnode, for example `` with Vue JSX or `h(PostHeader)`. + */ +export type CreateIsolatedTestRouterOptions< + TRouteTree extends AnyRoute, + TId, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, +> = IsolatedTestRouterOptions< + TRouteTree, + TId, + VNode, + TTrailingSlashOption, + TDefaultStructuralSharingOption +> + +/** + * Creates a router for a test, over a copy of the route tree. It takes the + * options of `createRouter`, plus `location` and `overrides`. Every route runs + * the application's own options unless `overrides` replaces them. Without a + * `history`, the router uses a memory history. + * + * The router has not loaded yet. Render it with `RouterProvider`, or call + * `router.load()` first. + * + * ```tsx + * const router = createTestRouter({ + * routeTree, + * context: { queryClient }, + * location: { to: '/posts/$postId', params: { postId: '1' } }, + * overrides: { '/posts/$postId': { loaderData: { post } } }, + * }) + * render() + * ``` + */ +export function createTestRouter< + TRouteTree extends AnyRoute, + const TLocation = unknown, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, + TRouterHistory extends RouterHistory = RouterHistory, + TDehydrated extends Record = Record, +>( + options: CreateTestRouterOptions< + TRouteTree, + TLocation, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated + >, +): Router< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated +> { + return createTestRouterWith(createRouter, options as any) as any +} + +/** + * Creates a router that renders one element inside one route, with the state + * the test supplies. It resolves once the router has loaded, so the first + * render of `` is complete. + * + * No `context`, `beforeLoad` or `loader` of any route runs, and no route + * component renders. The options are typed from the route: they ask for the + * context and the loader data those options would have produced. + * + * ```tsx + * const router = await createIsolatedTestRouter({ + * routeTree, + * route: '/posts/$postId', + * element: , + * params: { postId: '1' }, + * loaderData: { '/posts/$postId': { post } }, + * }) + * render() + * ``` + */ +export function createIsolatedTestRouter< + TRouteTree extends AnyRoute, + // `IsolatedTestRouterOptions` checks that `route` is a route id of the tree. + const TId extends string, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, +>( + options: CreateIsolatedTestRouterOptions< + TRouteTree, + TId, + TTrailingSlashOption, + TDefaultStructuralSharingOption + >, +): Promise< + Router +> { + const { element, ...state } = options as any + // A functional component that renders the vnode under test. + return createIsolatedTestRouterWith(createRouter, { + ...state, + component: () => element, + }) as any +} diff --git a/packages/vue-router/tests/testing.test-d.tsx b/packages/vue-router/tests/testing.test-d.tsx new file mode 100644 index 0000000000..dfdc32f630 --- /dev/null +++ b/packages/vue-router/tests/testing.test-d.tsx @@ -0,0 +1,102 @@ +import { describe, expectTypeOf, test } from 'vitest' +import { createRootRouteWithContext, createRoute, rootRouteId } from '../src' +import { createIsolatedTestRouter, createTestRouter } from '../src/testing' +import type { Router } from '../src' +import type { IsolatedRouteState } from '../src/testing' + +interface User { + id: string +} + +const rootRoute = createRootRouteWithContext<{ locale: string }>()({ + beforeLoad: (): { session: { user: User | null } } => ({ + session: { user: null }, + }), +}) + +const authedRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authed', + beforeLoad: ({ context }) => ({ user: context.session.user as User }), + loader: () => ({ unreadCount: 1 }), +}) + +const postRoute = createRoute({ + getParentRoute: () => authedRoute, + path: '/posts/$postId', + loader: ({ params }) => ({ post: { id: params.postId } }), +}) + +const routeTree = rootRoute.addChildren([authedRoute.addChildren([postRoute])]) + +type RouteTree = typeof routeTree + +type RequiredKeys = { + [K in keyof T]-?: {} extends Pick ? never : K +}[keyof T] + +const postState = { + routeTree, + route: '/_authed/posts/$postId', + element:
, + params: { postId: '1' }, + context: { locale: 'en', session: { user: null }, user: { id: '1' } }, + loaderData: { + '/_authed': { unreadCount: 1 }, + '/_authed/posts/$postId': { post: { id: '1' } }, + }, +} as const + +describe('createIsolatedTestRouter', () => { + test('asks for everything the route promises to its components', () => { + type PostState = IsolatedRouteState + + expectTypeOf>().toEqualTypeOf< + 'route' | 'params' | 'context' | 'loaderData' + >() + expectTypeOf>().toEqualTypeOf< + '/_authed' | '/_authed/posts/$postId' + >() + }) + + test('resolves to the Vue router type', () => { + expectTypeOf(createIsolatedTestRouter(postState)).toEqualTypeOf< + Promise> + >() + }) + + test('rejects state that is incomplete', () => { + const withoutAncestorLoaderData = { + ...postState, + loaderData: { '/_authed/posts/$postId': { post: { id: '1' } } }, + } as const + // @ts-expect-error the loader data of `/_authed` is missing + void createIsolatedTestRouter(withoutAncestorLoaderData) + }) +}) + +describe('createTestRouter', () => { + test('returns the Vue router type and types the overrides', () => { + expectTypeOf( + createTestRouter({ + routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: '1' } }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: { id: '1' } } } }, + '/_authed/posts/$postId': { + loader: ({ params }) => ({ post: { id: params.postId } }), + }, + }, + }), + ).toEqualTypeOf>() + + const wrongSeed = { + routeTree, + context: { locale: 'en' }, + overrides: { '/_authed': { loaderData: { unreadCount: 'many' } } }, + } as const + // @ts-expect-error `unreadCount` is a number + createTestRouter(wrongSeed) + }) +}) diff --git a/packages/vue-router/tests/testing.test.tsx b/packages/vue-router/tests/testing.test.tsx new file mode 100644 index 0000000000..f85b214cba --- /dev/null +++ b/packages/vue-router/tests/testing.test.tsx @@ -0,0 +1,245 @@ +import { afterEach, describe, expect, test } from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/vue' +import { defineComponent } from 'vue' +import { + Link, + Outlet, + RouterProvider, + createRootRouteWithContext, + createRoute, + redirect, + rootRouteId, +} from '../src' +import { createIsolatedTestRouter, createTestRouter } from '../src/testing' + +afterEach(() => { + cleanup() +}) + +interface User { + id: string + name: string +} + +interface Session { + user: User | null +} + +const realUser: User = { id: 'real', name: 'Real user' } +const testUser: User = { id: 'test', name: 'Test user' } + +function createApp() { + const calls: Array = [] + + const rootRoute = createRootRouteWithContext<{ locale: string }>()({ + beforeLoad: (): { session: Session } => { + calls.push('root.beforeLoad') + return { session: { user: realUser } } + }, + component: () => ( +
+

App shell

+ +
+ ), + }) + + const authedRoute = createRoute({ + getParentRoute: () => rootRoute, + id: '_authed', + beforeLoad: ({ context }) => { + calls.push('authed.beforeLoad') + if (!context.session.user) { + throw redirect({ to: '/login' }) + } + return { user: context.session.user } + }, + loader: () => { + calls.push('authed.loader') + return { unreadCount: 1 } + }, + component: () => ( +
+

Authed layout

+ +
+ ), + }) + + const postRoute = createRoute({ + getParentRoute: () => authedRoute, + path: '/posts/$postId', + loader: ({ params }) => { + calls.push('post.loader') + return { post: { id: params.postId, title: 'Real post' } } + }, + component: () => , + }) + + // Reads the state of its own route and of an ancestor through the route + // objects, the way components in route files do. + const PostHeader = defineComponent({ + setup() { + const data = postRoute.useLoaderData() + const context = postRoute.useRouteContext() + const authedData = authedRoute.useLoaderData() + + return () => ( +
+

{data.value.post.title}

+

+ {`${context.value.user.name} reads post ${data.value.post.id} in ${context.value.locale} with ${authedData.value.unreadCount} unread`} +

+ Sign out +
+ ) + }, + }) + + const loginRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/login', + component: () =>

Login page

, + }) + + const routeTree = rootRoute.addChildren([ + authedRoute.addChildren([postRoute]), + loginRoute, + ]) + + return { routeTree, PostHeader, calls } +} + +describe('createTestRouter', () => { + test('runs the lifecycle of the application by default', async () => { + const app = createApp() + + const router = createTestRouter({ + routeTree: app.routeTree, + context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: '1' } }, + }) + render() + + expect( + await screen.findByText('Real user reads post 1 in en with 1 unread'), + ).toBeInTheDocument() + expect(screen.getByText('App shell')).toBeInTheDocument() + expect(app.calls).toEqual([ + 'root.beforeLoad', + 'authed.beforeLoad', + 'authed.loader', + 'post.loader', + ]) + }) + + test('replaces the options a test names and keeps the rest', async () => { + const app = createApp() + + const router = createTestRouter({ + routeTree: app.routeTree, + context: { locale: 'de' }, + location: { to: '/posts/$postId', params: { postId: '2' } }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: testUser } } }, + '/_authed': { loaderData: { unreadCount: 7 } }, + '/_authed/posts/$postId': { + loader: ({ params }) => ({ + post: { id: params.postId, title: 'Replaced post' }, + }), + }, + }, + }) + render() + + expect( + await screen.findByText('Test user reads post 2 in de with 7 unread'), + ).toBeInTheDocument() + expect(screen.getByRole('heading')).toHaveTextContent('Replaced post') + expect(app.calls).toEqual(['authed.beforeLoad']) + }) +}) + +describe('createIsolatedTestRouter', () => { + test('renders one element in one route with the state the test supplies', async () => { + const app = createApp() + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: '5' }, + context: { locale: 'en', session: { user: testUser }, user: testUser }, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } }, + }, + }) + render() + + // The router has loaded, so the first render is complete. + expect(await screen.findByRole('heading')).toHaveTextContent('Seeded post') + expect( + screen.getByText('Test user reads post 5 in en with 4 unread'), + ).toBeInTheDocument() + expect(app.calls).toEqual([]) + expect(screen.queryByText('App shell')).not.toBeInTheDocument() + expect(screen.queryByText('Authed layout')).not.toBeInTheDocument() + }) + + test('navigates with the real router and renders no other route', async () => { + const app = createApp() + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/_authed/posts/$postId', + element: , + params: { postId: '5' }, + context: { locale: 'en', session: { user: testUser }, user: testUser }, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } }, + }, + }) + render() + + await fireEvent.click(await screen.findByRole('link', { name: 'Sign out' })) + + await waitFor(() => { + expect(router.state.location.pathname).toBe('/login') + }) + expect(screen.queryByText('Login page')).not.toBeInTheDocument() + expect(app.calls).toEqual([]) + }) + + test('passes the other options to the router', async () => { + const app = createApp() + const Providers = defineComponent({ + setup(_, { slots }) { + return () => ( +
{slots.default?.()}
+ ) + }, + }) + + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, + route: '/login', + element:

Element

, + context: { locale: 'en', session: { user: null } }, + // Vue renders `Wrap` with a default slot, as in RouterProvider.test.tsx. + Wrap: Providers as any, + }) + render() + + expect(await screen.findByLabelText('Providers')).toHaveTextContent( + 'Element', + ) + }) +}) diff --git a/packages/vue-router/vite.config.ts b/packages/vue-router/vite.config.ts index 13928e0a1a..6355c72f41 100644 --- a/packages/vue-router/vite.config.ts +++ b/packages/vue-router/vite.config.ts @@ -37,6 +37,7 @@ export default mergeConfig( './src/index.dev.tsx', './src/ssr/client.ts', './src/ssr/server.ts', + './src/testing.ts', ], srcDir: './src', cjs: false, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 4328f4fab6..a64e1f009e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1611,6 +1611,43 @@ importers: specifier: ^8.3.4 version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + e2e/react-router/route-testing: + dependencies: + '@tanstack/react-router': + specifier: workspace:* + version: link:../../../packages/react-router + '@tanstack/router-plugin': + specifier: workspace:* + version: link:../../../packages/router-plugin + react: + specifier: ~19.2.9 + version: 19.2.9 + react-dom: + specifier: ~19.2.9 + version: 19.2.9(react@19.2.9) + devDependencies: + '@testing-library/react': + specifier: 'catalog:' + version: 16.3.0(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.9))(@types/react@19.2.9)(react-dom@19.2.9(react@19.2.9))(react@19.2.9) + '@types/react': + specifier: ^19.2.8 + version: 19.2.9 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.9) + '@vitejs/plugin-react': + specifier: 'catalog:' + version: 6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.2.13)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + jsdom: + specifier: 'catalog:' + version: 25.0.1(supports-color@10.2.2) + vite: + specifier: ^8.3.4 + version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vitest: + specifier: 'catalog:' + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + e2e/react-router/rspack-basic-file-based: dependencies: '@tanstack/react-router': @@ -6844,6 +6881,34 @@ importers: specifier: ^8.3.4 version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + e2e/vue-router/route-testing: + dependencies: + '@tanstack/router-plugin': + specifier: workspace:* + version: link:../../../packages/router-plugin + '@tanstack/vue-router': + specifier: workspace:* + version: link:../../../packages/vue-router + vue: + specifier: 'catalog:' + version: 3.5.25(typescript@6.0.2) + devDependencies: + '@testing-library/vue': + specifier: ^8.1.0 + version: 8.1.0(@vue/compiler-sfc@3.5.25)(vue@3.5.25(typescript@6.0.2)) + '@vitejs/plugin-vue-jsx': + specifier: 'catalog:' + version: 4.2.0(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vue@3.5.25(typescript@6.0.2)) + jsdom: + specifier: 'catalog:' + version: 25.0.1(supports-color@10.2.2) + vite: + specifier: ^8.3.4 + version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vitest: + specifier: 'catalog:' + version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + e2e/vue-router/rspack-basic-file-based: dependencies: '@tanstack/vue-router': @@ -35729,6 +35794,15 @@ snapshots: optionalDependencies: '@vue/compiler-sfc': 3.5.25 + '@testing-library/vue@8.1.0(@vue/compiler-sfc@3.5.25)(vue@3.5.25(typescript@6.0.2))': + dependencies: + '@babel/runtime': 7.26.7 + '@testing-library/dom': 9.3.4 + '@vue/test-utils': 2.4.6 + vue: 3.5.25(typescript@6.0.2) + optionalDependencies: + '@vue/compiler-sfc': 3.5.25 + '@trpc/client@11.4.3(@trpc/server@11.4.3(@typescript/typescript6@6.0.2))(@typescript/typescript6@6.0.2)': dependencies: '@trpc/server': 11.4.3(@typescript/typescript6@6.0.2) @@ -36631,6 +36705,17 @@ snapshots: vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vitefu: 1.1.3(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + '@vitejs/plugin-vue-jsx@4.2.0(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vue@3.5.25(typescript@6.0.2))': + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) + '@babel/plugin-transform-typescript': 7.28.6(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + '@rolldown/pluginutils': 1.0.1 + '@vue/babel-plugin-jsx': 1.5.0(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2) + vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + vue: 3.5.25(typescript@6.0.2) + transitivePeerDependencies: + - supports-color + '@vitejs/plugin-vue-jsx@4.2.0(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vue@3.5.25(@typescript/typescript6@6.0.2))': dependencies: '@babel/core': 7.29.7(supports-color@10.2.2) @@ -36774,6 +36859,16 @@ snapshots: msw: 2.15.0(@types/node@25.0.9)(typescript@5.9.2) vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + '@vitest/mocker@5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))': + dependencies: + '@jridgewell/trace-mapping': 0.3.31 + '@vitest/spy': 5.0.4 + estree-walker: 3.0.3 + magic-string: 1.4.3 + optionalDependencies: + msw: 2.15.0(@types/node@25.0.9)(typescript@6.0.2) + vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + '@vitest/pretty-format@4.1.4': dependencies: tinyrainbow: 3.2.0 @@ -40400,7 +40495,7 @@ snapshots: cssstyle: 4.2.1 data-urls: 5.0.0 decimal.js: 10.6.0 - form-data: 4.0.5 + form-data: 4.0.6 html-encoding-sniffer: 4.0.0 http-proxy-agent: 7.0.2(supports-color@10.2.2) https-proxy-agent: 7.0.6(supports-color@10.2.2) @@ -40416,7 +40511,7 @@ snapshots: whatwg-encoding: 3.1.1 whatwg-mimetype: 4.0.0 whatwg-url: 14.1.0 - ws: 8.20.0 + ws: 8.21.0 xml-name-validator: 5.0.0 transitivePeerDependencies: - bufferutil @@ -41095,6 +41190,32 @@ snapshots: - '@types/node' optional: true + msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2): + dependencies: + '@inquirer/confirm': 6.3.2(@types/node@25.0.9) + '@mswjs/interceptors': 0.41.9 + '@open-draft/deferred-promise': 3.0.0 + '@types/statuses': 2.0.6 + cookie: 1.1.1 + graphql: 16.14.2 + headers-polyfill: 5.0.1 + is-node-process: 1.2.0 + outvariant: 1.4.3 + path-to-regexp: 6.3.0 + picocolors: 1.1.1 + rettime: 0.11.11 + statuses: 2.0.2 + strict-event-emitter: 0.5.1 + tough-cookie: 6.0.1 + type-fest: 5.9.0 + until-async: 3.0.2 + yargs: 17.7.2 + optionalDependencies: + typescript: 6.0.2 + transitivePeerDependencies: + - '@types/node' + optional: true + msw@2.7.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2): dependencies: '@bundled-es-modules/cookie': 2.0.1 @@ -44200,6 +44321,30 @@ snapshots: transitivePeerDependencies: - msw + vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): + dependencies: + '@types/chai': 5.2.2 + '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + chai: 6.3.0 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 1.4.3 + obug: 3.0.0 + picomatch: 4.0.7 + std-env: 4.3.0 + tinybench: 6.2.2 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) + why-is-node-running: 3.2.1 + optionalDependencies: + '@opentelemetry/api': 1.9.1 + '@types/node': 25.0.9 + '@vitest/ui': 5.0.4(vitest@5.0.4) + jsdom: 25.0.1(supports-color@10.2.2) + transitivePeerDependencies: + - msw + vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: '@types/chai': 5.2.2