From ca7e7130de2523197328e8c9b2cc00118b90a6af Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:19:52 +0100 Subject: [PATCH 1/8] feat(react-router): add experimental typed route testing utilities Add `@tanstack/react-router/testing` with `createRouterTesting`, which returns two helpers built from an app's route tree: - `createTestRouter` creates a router over a copy of the tree. Routes run their own lifecycle unless a test replaces `context`, `beforeLoad`, `loader` or a component option by route id, or seeds the route's context or loader data. - `renderInRoute` renders one element in one route. No lifecycle option runs, and the types require the params, search, context and loader data that the skipped options would have produced. The framework-independent part lives in `@tanstack/router-core/testing`. The new `e2e/react-router/route-testing` project uses the helpers for its own tests. Co-Authored-By: Claude Opus 5.5 --- .changeset/router-testing-utilities.md | 10 + e2e/react-router/route-testing/.gitignore | 4 + e2e/react-router/route-testing/package.json | 23 + e2e/react-router/route-testing/src/api.ts | 35 + .../src/components/PostHeader.tsx | 25 + .../route-testing/src/components/UserMenu.tsx | 16 + .../route-testing/src/routeTree.gen.ts | 119 +++ e2e/react-router/route-testing/src/router.tsx | 16 + .../route-testing/src/routes/__root.tsx | 26 + .../route-testing/src/routes/_authed.tsx | 23 + .../src/routes/_authed/posts.$postId.tsx | 35 + .../route-testing/src/routes/index.tsx | 16 + .../route-testing/src/routes/login.tsx | 21 + .../route-testing/src/test-utils.tsx | 41 + .../route-testing/tests/post-header.test.tsx | 101 +++ .../route-testing/tests/post-route.test.tsx | 146 ++++ .../tests/route-testing.test-d.tsx | 120 +++ e2e/react-router/route-testing/tests/setup.ts | 14 + .../route-testing/tests/user-menu.test.tsx | 44 ++ e2e/react-router/route-testing/tsconfig.json | 15 + e2e/react-router/route-testing/vite.config.ts | 23 + packages/react-router/package.json | 10 + packages/react-router/src/testing.tsx | 359 +++++++++ .../react-router/tests/testing.test-d.tsx | 352 +++++++++ packages/react-router/tests/testing.test.tsx | 713 ++++++++++++++++++ packages/react-router/vite.config.ts | 1 + packages/router-core/package.json | 10 + packages/router-core/src/testing/index.ts | 24 + packages/router-core/src/testing/routeTree.ts | 326 ++++++++ packages/router-core/src/testing/types.ts | 252 +++++++ packages/router-core/tests/testing.test.ts | 432 +++++++++++ packages/router-core/vite.config.ts | 1 + pnpm-lock.yaml | 128 +++- 33 files changed, 3478 insertions(+), 3 deletions(-) create mode 100644 .changeset/router-testing-utilities.md create mode 100644 e2e/react-router/route-testing/.gitignore create mode 100644 e2e/react-router/route-testing/package.json create mode 100644 e2e/react-router/route-testing/src/api.ts create mode 100644 e2e/react-router/route-testing/src/components/PostHeader.tsx create mode 100644 e2e/react-router/route-testing/src/components/UserMenu.tsx create mode 100644 e2e/react-router/route-testing/src/routeTree.gen.ts create mode 100644 e2e/react-router/route-testing/src/router.tsx create mode 100644 e2e/react-router/route-testing/src/routes/__root.tsx create mode 100644 e2e/react-router/route-testing/src/routes/_authed.tsx create mode 100644 e2e/react-router/route-testing/src/routes/_authed/posts.$postId.tsx create mode 100644 e2e/react-router/route-testing/src/routes/index.tsx create mode 100644 e2e/react-router/route-testing/src/routes/login.tsx create mode 100644 e2e/react-router/route-testing/src/test-utils.tsx create mode 100644 e2e/react-router/route-testing/tests/post-header.test.tsx create mode 100644 e2e/react-router/route-testing/tests/post-route.test.tsx create mode 100644 e2e/react-router/route-testing/tests/route-testing.test-d.tsx create mode 100644 e2e/react-router/route-testing/tests/setup.ts create mode 100644 e2e/react-router/route-testing/tests/user-menu.test.tsx create mode 100644 e2e/react-router/route-testing/tsconfig.json create mode 100644 e2e/react-router/route-testing/vite.config.ts create mode 100644 packages/react-router/src/testing.tsx create mode 100644 packages/react-router/tests/testing.test-d.tsx create mode 100644 packages/react-router/tests/testing.test.tsx create mode 100644 packages/router-core/src/testing/index.ts create mode 100644 packages/router-core/src/testing/routeTree.ts create mode 100644 packages/router-core/src/testing/types.ts create mode 100644 packages/router-core/tests/testing.test.ts diff --git a/.changeset/router-testing-utilities.md b/.changeset/router-testing-utilities.md new file mode 100644 index 0000000000..cf0508357e --- /dev/null +++ b/.changeset/router-testing-utilities.md @@ -0,0 +1,10 @@ +--- +'@tanstack/router-core': minor +'@tanstack/react-router': minor +--- + +Add typed test utilities for routes, exported from `@tanstack/react-router/testing`. + +`createRouterTesting({ routeTree })` returns two helpers. `createTestRouter` creates a router over a copy of the app's route tree: every route runs the app's own lifecycle unless the test replaces `context`, `beforeLoad`, `loader` or a component option for that route id, or seeds its context or loader data. `renderInRoute` 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 framework-independent part is exported from `@tanstack/router-core/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-utils.tsx b/e2e/react-router/route-testing/src/test-utils.tsx new file mode 100644 index 0000000000..d0ed65a186 --- /dev/null +++ b/e2e/react-router/route-testing/src/test-utils.tsx @@ -0,0 +1,41 @@ +import { render } from '@testing-library/react' +import { createRouterTesting } from '@tanstack/react-router/testing' +import { routeTree } from './routeTree.gen' +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, + } +} + +/** + * Test helpers without defaults. Every test supplies the whole state its + * route promises. + */ +export const routerTesting = createRouterTesting({ routeTree, render }) + +/** + * Test helpers with the values most tests of this app share. What is given + * here is optional in each test. + */ +export const appTesting = createRouterTesting({ + routeTree, + render, + defaults: { + context: { + locale: 'en', + session: { user: testUser }, + user: testUser, + }, + routes: { + '/_authed': { loaderData: { unreadCount: 0 } }, + }, + }, +}) 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..8d71e97de4 --- /dev/null +++ b/e2e/react-router/route-testing/tests/post-header.test.tsx @@ -0,0 +1,101 @@ +import { fireEvent, screen, waitFor } from '@testing-library/react' +import { describe, expect, test, vi } from 'vitest' +import { PostHeader } from '../src/components/PostHeader' +import { + appTesting, + createPost, + routerTesting, + testUser, +} from '../src/test-utils' + +describe('a component rendered in its route with supplied state', () => { + test('reads loader data, context, search and params of the route', async () => { + const fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) + + await routerTesting.renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: 'post-1' }, + context: { locale: 'en', session: { user: testUser }, user: testUser }, + loaderData: { + post: createPost({ title: 'Typed tests', authorId: testUser.id }), + }, + routes: { '/_authed': { loaderData: { unreadCount: 2 } } }, + }) + + 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) + + await routerTesting.renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: 'post-1' }, + context: { locale: 'en', session: { user: testUser }, user: testUser }, + loaderData: { post: createPost() }, + routes: { '/_authed': { loaderData: { unreadCount: 2 } } }, + }) + + expect(fetchMock).not.toHaveBeenCalled() + expect(screen.queryByRole('navigation')).toBeNull() + expect(screen.queryByLabelText('User menu')).toBeNull() + expect(screen.queryByLabelText('Tab content')).toBeNull() + }) + + test('takes shared values from the defaults of the application', async () => { + await appTesting.renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: 'post-1' }, + loaderData: { post: createPost({ status: 'draft' }) }, + }) + + expect(screen.getByText('Draft')).toBeTruthy() + expect(screen.queryByText('Written by you')).toBeNull() + }) + + test('sends search params through the validateSearch of the route', async () => { + await appTesting.renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: 'post-1' }, + search: { tab: 'comments' }, + loaderData: { post: createPost() }, + }) + + expect(screen.getByRole('link', { name: 'Show details' })).toBeTruthy() + }) + + test('fails when the search params do not pass validateSearch', async () => { + await expect( + appTesting.renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: 'post-1' }, + search: { tab: 'history' }, + loaderData: { post: createPost() }, + }), + ).rejects.toThrow('Unknown tab "history"') + }) + + test('navigates with the real router', async () => { + const { router } = await appTesting.renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: 'post-1' }, + loaderData: { post: createPost() }, + }) + + 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..f4fd68495c --- /dev/null +++ b/e2e/react-router/route-testing/tests/post-route.test.tsx @@ -0,0 +1,146 @@ +import { render, screen, waitFor } from '@testing-library/react' +import { RouterProvider } from '@tanstack/react-router' +import { describe, expect, test, vi } from 'vitest' +import { createPost, routerTesting, testUser } from '../src/test-utils' +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 = routerTesting.createTestRouter({ + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + context: { locale: 'en' }, + }) + 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 = routerTesting.createTestRouter({ + location: { + to: '/posts/$postId', + params: { postId: 'post-1' }, + search: { tab: 'comments' }, + }, + context: { locale: 'en' }, + }) + 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 = routerTesting.createTestRouter({ + location: { to: '/posts/$postId', params: { postId: 'post-7' } }, + context: { locale: 'en' }, + routes: { + // A seed: the session lookup of the root route does not run. + __root__: { context: { 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 = routerTesting.createTestRouter({ + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + context: { locale: 'en' }, + routes: { + '/_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 = routerTesting.createTestRouter({ + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + context: { locale: 'en' }, + routes: { + __root__: { context: { 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 = routerTesting.createTestRouter({ + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + context: { locale: 'en' }, + }) + 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..fa7709113a --- /dev/null +++ b/e2e/react-router/route-testing/tests/route-testing.test-d.tsx @@ -0,0 +1,120 @@ +import { describe, expectTypeOf, test } from 'vitest' +import { PostHeader } from '../src/components/PostHeader' +import { + appTesting, + createPost, + routerTesting, + testUser, +} from '../src/test-utils' +import type { Post, Session, User } from '../src/api' + +const postState = { + route: '/_authed/posts/$postId', + params: { postId: 'post-1' }, + context: { locale: 'en', session: { user: testUser }, user: testUser }, + loaderData: { post: createPost() }, + routes: { '/_authed': { loaderData: { unreadCount: 0 } } }, +} as const + +describe('renderInRoute is typed from the generated route tree', () => { + test('accepts the complete state of a route', () => { + void routerTesting.renderInRoute(, 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 routerTesting.renderInRoute(, withoutUser) + }) + + test('rejects missing loader data of the route and of its ancestors', () => { + const { loaderData: _loaderData, ...withoutLoaderData } = postState + // @ts-expect-error the loader data of the route is missing + void routerTesting.renderInRoute(, withoutLoaderData) + + const { routes: _routes, ...withoutAncestors } = postState + // @ts-expect-error the loader data of `/_authed` is missing + void routerTesting.renderInRoute(, withoutAncestors) + }) + + test('rejects loader data of the wrong shape', () => { + const wrongPost = { + ...postState, + loaderData: { post: { id: 'post-1', title: 'No status' } }, + } as const + // @ts-expect-error `authorId` and `status` are missing from the post + void routerTesting.renderInRoute(, 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 routerTesting.renderInRoute(, unknownRoute) + }) + + test('makes optional what the defaults of the application provide', () => { + const onlyOwnState = { + route: '/_authed/posts/$postId', + params: { postId: 'post-1' }, + loaderData: { post: createPost() }, + } as const + void appTesting.renderInRoute(, onlyOwnState) + + // @ts-expect-error without defaults the context and the ancestors are required + void routerTesting.renderInRoute(, onlyOwnState) + }) +}) + +describe('createTestRouter is typed from the generated route tree', () => { + test('types a replacement like the option it replaces', () => { + routerTesting.createTestRouter({ + context: { locale: 'en' }, + routes: { + __root__: { + 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 = { + context: { locale: 'en' }, + routes: { + '/_authed/posts/$postId': { + loader: (): { post: Pick } => ({ post: { id: '1' } }), + }, + }, + } + // @ts-expect-error the loader has to return a whole post + routerTesting.createTestRouter(wrongLoader) + }) + + test('types the start location like a link', () => { + const withoutParams = { + context: { locale: 'en' }, + location: { to: '/posts/$postId' }, + } as const + // @ts-expect-error the path params are missing + routerTesting.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..d90ad195a2 --- /dev/null +++ b/e2e/react-router/route-testing/tests/user-menu.test.tsx @@ -0,0 +1,44 @@ +import { fireEvent, screen, waitFor } from '@testing-library/react' +import { describe, expect, test } from 'vitest' +import { UserMenu } from '../src/components/UserMenu' +import { appTesting, createPost, testUser } from '../src/test-utils' + +describe('a component bound to a layout route', () => { + test('is rendered through a child route and reads the state of the layout route', async () => { + await appTesting.renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: 'post-1' }, + context: { user: { id: 'user-9', name: 'Grace' } }, + loaderData: { post: createPost() }, + routes: { '/_authed': { loaderData: { unreadCount: 7 } } }, + }) + + 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 appTesting.renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: 'post-1' }, + loaderData: { post: createPost() }, + }) + + 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( + appTesting.renderInRoute(, { + route: '/_authed', + context: { user: testUser }, + }), + ).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/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.tsx b/packages/react-router/src/testing.tsx new file mode 100644 index 0000000000..80e3f0122c --- /dev/null +++ b/packages/react-router/src/testing.tsx @@ -0,0 +1,359 @@ +import { createMemoryHistory } from '@tanstack/history' +import { + assertIsolatedRouteLoaded, + assertRouteTestParams, + createIsolatedRouteTree, + createTestRouteTree, + setTestRouterLocation, +} from '@tanstack/router-core/testing' +import { RouterProvider } from './RouterProvider' +import { createRouter } from './router' +import type * as React from 'react' +import type { RouterHistory } from '@tanstack/history' +import type { + AnyRoute, + RouteIds, + RouterOptions, + TrailingSlashOption, + ValidateNavigateOptions, +} from '@tanstack/router-core' +import type { + AnyRouteTestOverrides, + RouteTestOverrides as CoreRouteTestOverrides, + RouterTestingDefaults as CoreRouterTestingDefaults, + RouteTestOptions, + TestRouterContextOption, +} from '@tanstack/router-core/testing' +import type { + ErrorRouteComponent, + NotFoundRouteComponent, + RouteComponent, +} from './route' +import type { Router } from './router' + +export type { + RouteTestBeforeLoadFn, + RouteTestContextFn, + RouteTestLoaderFn, + RouteTestOptions, +} 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. */ +export type RouteTestOverrides = + CoreRouteTestOverrides + +/** Defaults an application sets once for all of its route tests. */ +export type RouterTestingDefaults = + CoreRouterTestingDefaults + +/** + * Renders the element a test hands over, for example `render` from + * `@testing-library/react` or from `vitest-browser-react`. + */ +export type RouterTestingRenderFn = (ui: React.ReactElement) => unknown + +/** Router options shared by every test router. */ +export type TestRouterBaseOptions< + TRouteTree extends AnyRoute, + TTrailingSlashOption extends TrailingSlashOption, + TDefaultStructuralSharingOption extends boolean, +> = Omit< + RouterOptions< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + RouterHistory, + Record + >, + 'routeTree' | 'history' | 'context' +> + +export interface RouterTestingConfig< + TRouteTree extends AnyRoute, + TTrailingSlashOption extends TrailingSlashOption, + TDefaultStructuralSharingOption extends boolean, + TDefaults, + TRender, +> { + /** The application's route tree. Every test router is built from a copy. */ + routeTree: TRouteTree + /** + * Router options for every test router, such as `Wrap` for providers. The + * tree, the history and the context are set per test. + */ + routerOptions?: TestRouterBaseOptions< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption + > + /** + * Context values and overrides every test starts with. What is given here + * becomes optional in each test. + */ + // The intersection lets functions inside the defaults take their parameter + // types from the route tree while `TDefaults` records what was given. + defaults?: TDefaults & RouterTestingDefaults + /** + * The render function of the test library. Needed for `renderInRoute`. + */ + render?: TRender +} + +export type CreateTestRouterOptions< + TRouteTree extends AnyRoute, + TTrailingSlashOption extends TrailingSlashOption, + TDefaultStructuralSharingOption extends boolean, + TDefaults, + TLocation, +> = { + /** + * Where the router starts, typed like the options of `navigate`. Defaults + * to `/`. + */ + location?: ValidateNavigateOptions< + Router, + TLocation + > + /** + * A history to start from instead of `location`, for entries that are not + * valid navigation targets. + */ + history?: RouterHistory + /** + * Per-route overrides. A route that is not listed keeps the application's + * options. + */ + routes?: RouteTestOverrides +} & TestRouterContextOption + +export type RenderInRouteOptions< + TRouteTree extends AnyRoute, + TId, + TDefaults, +> = RouteTestOptions + +export interface RenderInRouteResult< + TRouteTree extends AnyRoute, + TTrailingSlashOption extends TrailingSlashOption, + TDefaultStructuralSharingOption extends boolean, + TRender, +> { + router: Router< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption + > + /** What the configured `render` function returned. */ + result: TRender extends (...args: Array) => infer TResult + ? Awaited + : never +} + +export interface RouterTesting< + TRouteTree extends AnyRoute, + TTrailingSlashOption extends TrailingSlashOption, + TDefaultStructuralSharingOption extends boolean, + TDefaults, + TRender, +> { + /** + * Creates a router over a copy of the route tree. Every route runs the + * application's own lifecycle unless `routes` replaces part of it. + * + * The router has not loaded yet. Render it with `RouterProvider`, or call + * `router.load()` first when the test needs the first render to be complete. + */ + createTestRouter: ( + ...args: {} extends CreateTestRouterOptions< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TDefaults, + TLocation + > + ? [ + options?: CreateTestRouterOptions< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TDefaults, + TLocation + >, + ] + : [ + options: CreateTestRouterOptions< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TDefaults, + TLocation + >, + ] + ) => Router + /** + * Renders one element inside one route, with the route's state supplied by + * the test. + * + * 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. + */ + renderInRoute: >( + element: React.ReactElement, + options: RenderInRouteOptions, + ) => Promise< + RenderInRouteResult< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRender + > + > +} + +interface AnyRenderInRouteOptions { + route: string + params?: Record + search?: Record + context?: Record + loaderData?: unknown + routes?: Record +} + +interface AnyCreateTestRouterOptions { + location?: object + history?: RouterHistory + routes?: AnyRouteTestOverrides + context?: Record +} + +interface AnyRouterTestingDefaults { + context?: Record + routes?: AnyRouteTestOverrides +} + +/** + * Creates the test helpers for one application. Call it once, for example in + * a `test-utils` file, with the application's route tree. + * + * ```tsx + * import { render } from '@testing-library/react' + * import { createRouterTesting } from '@tanstack/react-router/testing' + * import { routeTree } from './routeTree.gen' + * + * export const { createTestRouter, renderInRoute } = createRouterTesting({ + * routeTree, + * render, + * }) + * ``` + */ +export function createRouterTesting< + TRouteTree extends AnyRoute, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, + const TDefaults = {}, + TRender extends RouterTestingRenderFn | undefined = undefined, +>( + config: RouterTestingConfig< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TDefaults, + TRender + >, +): RouterTesting< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TDefaults, + TRender +> { + const defaults = config.defaults as AnyRouterTestingDefaults | undefined + + const createTestRouter = (options: AnyCreateTestRouterOptions = {}) => { + const router = createRouter({ + ...config.routerOptions, + routeTree: createTestRouteTree( + config.routeTree, + defaults?.routes, + options.routes, + ), + history: options.history ?? createMemoryHistory(), + context: { ...defaults?.context, ...options.context }, + } as any) + + if (options.location && !options.history) { + setTestRouterLocation(router, options.location) + } + + return router + } + + const renderInRoute = async ( + element: React.ReactElement, + options: AnyRenderInRouteOptions, + ) => { + const render = config.render + if (!render) { + throw new Error( + 'renderInRoute needs a render function. Pass `render` to createRouterTesting, for example the one from @testing-library/react.', + ) + } + + const loaderData = new Map() + const seedLoaderData = ( + routes: Record | undefined, + ) => { + for (const routeId in routes) { + const seed = routes[routeId] + if (seed && 'loaderData' in seed) { + loaderData.set(routeId, seed.loaderData) + } + } + } + seedLoaderData(defaults?.routes) + seedLoaderData(options.routes) + if ('loaderData' in options) { + loaderData.set(options.route, options.loaderData) + } + + const router = createRouter({ + ...config.routerOptions, + // Nothing of the application renders around the element, and an error + // it throws reaches the test instead of an error component. + defaultComponent: undefined, + defaultErrorComponent: undefined, + defaultPendingComponent: undefined, + disableGlobalCatchBoundary: true, + routeTree: createIsolatedRouteTree(config.routeTree, { + routeId: options.route, + component: () => element, + loaderData, + }), + history: createMemoryHistory(), + context: { ...defaults?.context, ...options.context }, + } as any) + + assertRouteTestParams(router, options.route, options.params) + setTestRouterLocation(router, { + to: router.routesById[options.route]!.fullPath, + params: options.params, + search: options.search, + }) + await router.load() + assertIsolatedRouteLoaded(router, options.route) + + const result = await render() + return { router, result } + } + + return { createTestRouter, renderInRoute } 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..b3ce80319f --- /dev/null +++ b/packages/react-router/tests/testing.test-d.tsx @@ -0,0 +1,352 @@ +import { render } from '@testing-library/react' +import { describe, expectTypeOf, test } from 'vitest' +import { createRootRouteWithContext, createRoute } from '../src' +import { createRouterTesting } from '../src/testing' +import type * as React from 'react' +import type { RenderResult } from '@testing-library/react' +import type { Router, SearchSchemaInput } from '../src' +import type { RenderInRouteOptions } 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 testing = createRouterTesting({ routeTree, render }) + +const testingWithDefaults = createRouterTesting({ + routeTree, + render, + defaults: { + context: { locale: 'en', user: { id: 'default' } }, + routes: { '/_authed': { loaderData: { unreadCount: 0 } } }, + }, +}) + +const postState = { + route: '/_authed/posts/$postId', + params: { postId: '1' }, + context: { locale: 'en', session: { user: null }, user: { id: '1' } }, + loaderData: { post: { id: '1' } }, + routes: { '/_authed': { loaderData: { unreadCount: 1 } } }, +} as const + +describe('renderInRoute', () => { + test('asks for everything the route promises to its components', () => { + type PostOptions = RenderInRouteOptions< + RouteTree, + '/_authed/posts/$postId', + {} + > + + expectTypeOf>().toEqualTypeOf< + 'route' | 'params' | 'context' | 'loaderData' | 'routes' + >() + expectTypeOf< + PostOptions['route'] + >().toEqualTypeOf<'/_authed/posts/$postId'>() + expectTypeOf().toEqualTypeOf<'postId'>() + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf< + 'locale' | 'session' | 'user' + >() + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf<{ + post: { id: string } + }>() + expectTypeOf().toEqualTypeOf<{ + loaderData: { unreadCount: number } + }>() + expectTypeOf>().toEqualTypeOf<{ + tab?: string + }>() + }) + + test('asks for nothing a route does not have', () => { + type SettingsOptions = RenderInRouteOptions< + RouteTree, + '/_authed/settings', + {} + > + // No path params and no loader of its own, but an ancestor with a loader. + expectTypeOf>().toEqualTypeOf< + 'route' | 'context' | 'routes' + >() + + type LoginOptions = RenderInRouteOptions + // Its beforeLoad adds nothing, so the context is the one of the root route. + expectTypeOf>().toEqualTypeOf< + 'route' | 'context' + >() + expectTypeOf().toEqualTypeOf< + 'locale' | 'session' + >() + }) + + test('accepts the complete state and returns the router and the render result', async () => { + const rendered = await testing.renderInRoute(
, postState) + + expectTypeOf(rendered.router).toEqualTypeOf< + Router + >() + expectTypeOf(rendered.result).toEqualTypeOf() + }) + + 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 testing.renderInRoute(
, withoutContext) + + const withoutUser = { + ...postState, + context: { locale: 'en', session: { user: null } }, + } as const + // @ts-expect-error `user` is missing from the context + void testing.renderInRoute(
, withoutUser) + + const { loaderData: _loaderData, ...withoutLoaderData } = postState + // @ts-expect-error the loader data of the route is missing + void testing.renderInRoute(
, withoutLoaderData) + + const { routes: _routes, ...withoutAncestors } = postState + // @ts-expect-error the loader data of `/_authed` is missing + void testing.renderInRoute(
, withoutAncestors) + + const { params: _params, ...withoutParams } = postState + // @ts-expect-error the path params are missing + void testing.renderInRoute(
, withoutParams) + + const wrongLoaderData = { ...postState, loaderData: { post: 1 } } as const + // @ts-expect-error `post` is not a number + void testing.renderInRoute(
, wrongLoaderData) + + const unknownRoute = { ...postState, route: '/unknown' } as const + // @ts-expect-error not a route id of the tree + void testing.renderInRoute(
, unknownRoute) + }) + + test('makes optional what the defaults of the application provide', () => { + const { routes: _routes, ...withoutAncestors } = postState + const withDefaults = { + ...withoutAncestors, + context: { session: { user: null } }, + } as const + void testingWithDefaults.renderInRoute(
, withDefaults) + + const withoutSession = { ...withoutAncestors, context: {} } as const + // @ts-expect-error `session` is not among the defaults + void testingWithDefaults.renderInRoute(
, withoutSession) + + type PostOptions = RenderInRouteOptions< + RouteTree, + '/_authed/posts/$postId', + { + context: { locale: string; user: User } + routes: { '/_authed': { loaderData: { unreadCount: number } } } + } + > + expectTypeOf>().toEqualTypeOf< + 'route' | 'params' | 'context' | 'loaderData' + >() + expectTypeOf< + RequiredKeys + >().toEqualTypeOf<'session'>() + }) +}) + +describe('createRouterTesting', () => { + test('types the defaults from the route tree', () => { + createRouterTesting({ + routeTree, + defaults: { + context: { locale: 'en', session: { user: null } }, + routes: { + '/_authed': { + beforeLoad: ({ context }) => { + expectTypeOf(context.session).toEqualTypeOf() + return { user: { id: '1' } } + }, + }, + }, + }, + }) + + createRouterTesting({ + routeTree, + // @ts-expect-error `locale` is a string + defaults: { context: { locale: 1 } }, + }) + }) + + test('takes the type of the render result from the render function', async () => { + const withAsyncRender = createRouterTesting({ + routeTree, + render: (ui: React.ReactElement) => Promise.resolve({ ui }), + }) + const rendered = await withAsyncRender.renderInRoute(
, postState) + + expectTypeOf(rendered.result).toEqualTypeOf<{ ui: React.ReactElement }>() + }) +}) + +describe('createTestRouter', () => { + test('returns the router type of the route tree', () => { + expectTypeOf( + testing.createTestRouter({ context: { locale: 'en' } }), + ).toEqualTypeOf>() + }) + + test('requires the router context unless the defaults provide it', () => { + // @ts-expect-error the router context is required + testing.createTestRouter() + + const withoutContext = {} as const + // @ts-expect-error the router context is required + testing.createTestRouter(withoutContext) + + testingWithDefaults.createTestRouter() + }) + + test('types the location like navigation options', () => { + testing.createTestRouter({ + context: { locale: 'en' }, + location: { + to: '/posts/$postId', + params: { postId: '1' }, + search: { tab: 'comments' }, + }, + }) + + const withoutParams = { + context: { locale: 'en' }, + location: { to: '/posts/$postId' }, + } as const + // @ts-expect-error the path params of the location are missing + testing.createTestRouter(withoutParams) + + const unknownPath = { + context: { locale: 'en' }, + location: { to: '/unknown' }, + } as const + // @ts-expect-error not a path of the tree + testing.createTestRouter(unknownPath) + }) + + test('types replacements and seeds from the route', () => { + testing.createTestRouter({ + context: { locale: 'en' }, + routes: { + __root__: { context: { 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: () => {}, + }, + }, + }) + }) + + test('rejects replacements and seeds of the wrong type', () => { + const wrongSeed = { + context: { locale: 'en' }, + routes: { '/_authed': { loaderData: { unreadCount: 'many' } } }, + } as const + // @ts-expect-error `unreadCount` is a number + testing.createTestRouter(wrongSeed) + + const wrongContextSeed = { + context: { locale: 'en' }, + routes: { '/_authed': { context: { user: 'nobody' } } }, + } as const + // @ts-expect-error `user` is an object + testing.createTestRouter(wrongContextSeed) + + const wrongLoader = { + context: { locale: 'en' }, + routes: { + '/_authed/posts/$postId': { loader: () => ({ post: 'none' }) }, + }, + } + // @ts-expect-error the loader has to return the loader data of the route + testing.createTestRouter(wrongLoader) + + const wrongBeforeLoad = { + context: { locale: 'en' }, + routes: { '/_authed': { beforeLoad: () => ({ user: 'nobody' }) } }, + } + // @ts-expect-error beforeLoad has to return what the route's own returns + testing.createTestRouter(wrongBeforeLoad) + + const unknownRoute = { + context: { locale: 'en' }, + routes: { '/unknown': {} }, + } as const + // @ts-expect-error not a route id of the tree + testing.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..44c943f32c --- /dev/null +++ b/packages/react-router/tests/testing.test.tsx @@ -0,0 +1,713 @@ +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, +} from '../src' +import { createRouterTesting } 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, + } +} + +describe('createTestRouter', () => { + test('runs the lifecycle of the application by default', async () => { + const app = createApp() + const { createTestRouter } = createRouterTesting({ + routeTree: app.routeTree, + }) + + const router = createTestRouter({ + 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 { createTestRouter } = createRouterTesting({ + routeTree: app.routeTree, + }) + + const router = createTestRouter({ + location: { + to: '/posts/$postId', + params: { postId: '2' }, + search: { tab: 'comments' }, + }, + context: { locale: 'de' }, + routes: { + __root__: { context: { 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 { createTestRouter } = createRouterTesting({ + routeTree: app.routeTree, + }) + + const router = createTestRouter({ + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'en' }, + routes: { + '/_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 { createTestRouter } = createRouterTesting({ + routeTree: app.routeTree, + }) + + const router = createTestRouter({ + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'en' }, + routes: { '/_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 { createTestRouter } = createRouterTesting({ + routeTree: app.routeTree, + }) + + const first = createTestRouter({ + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'en' }, + routes: { + '/_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({ + 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() + + createRouterTesting({ routeTree: app.routeTree }).createTestRouter({ + 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('starts from a history instead of a location', async () => { + const app = createApp() + const { createTestRouter } = createRouterTesting({ + routeTree: app.routeTree, + }) + + const router = createTestRouter({ + history: createMemoryHistory({ initialEntries: ['/login'] }), + context: { locale: 'en' }, + }) + render() + + expect(await screen.findByText('Login page')).toBeInTheDocument() + }) + + test('lets an override win over the options of a lazy route', async () => { + const app = createApp() + const { createTestRouter } = createRouterTesting({ + routeTree: app.routeTree, + }) + + const real = createTestRouter({ + location: { to: '/lazy' }, + context: { locale: 'en' }, + }) + const { unmount } = render() + expect(await screen.findByText('Lazy component')).toBeInTheDocument() + unmount() + + const overridden = createTestRouter({ + location: { to: '/lazy' }, + context: { locale: 'en' }, + routes: { '/lazy': { component: () =>

Test component

} }, + }) + render() + expect(await screen.findByText('Test component')).toBeInTheDocument() + expect(screen.queryByText('Lazy component')).not.toBeInTheDocument() + }) + + test('applies the defaults of the application, and a test wins over them', async () => { + const app = createApp() + const { createTestRouter } = createRouterTesting({ + routeTree: app.routeTree, + defaults: { + context: { locale: 'fr' }, + routes: { + __root__: { context: { session: { user: testUser } } }, + '/_authed': { loaderData: { unreadCount: 3 } }, + }, + }, + }) + + const withDefaults = createTestRouter({ + location: { to: '/posts/$postId', params: { postId: '1' } }, + }) + const { unmount } = render() + expect( + await screen.findByText( + 'Test user reads post 1 in fr on tab details with 3 unread in real scope', + ), + ).toBeInTheDocument() + unmount() + + const withOwnValues = createTestRouter({ + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'it' }, + routes: { '/_authed': { loaderData: { unreadCount: 9 } } }, + }) + render() + expect( + await screen.findByText( + 'Test user reads post 1 in it on tab details with 9 unread in real scope', + ), + ).toBeInTheDocument() + }) + + test('rejects an override for a route that does not exist', () => { + const app = createApp() + const { createTestRouter } = createRouterTesting({ + routeTree: app.routeTree, + }) + + expect(() => + createTestRouter({ + context: { locale: 'en' }, + // @ts-expect-error not a route id of this tree + routes: { '/missing': { component: () => null } }, + }), + ).toThrow('The route "/missing" does not exist in the route tree') + }) + + test('rejects an override with both a loader and loader data', () => { + const app = createApp() + const { createTestRouter } = createRouterTesting({ + routeTree: app.routeTree, + }) + + expect(() => + createTestRouter({ + context: { locale: 'en' }, + routes: { + '/_authed': { + loader: () => ({ unreadCount: 1 }), + loaderData: { unreadCount: 2 }, + }, + }, + }), + ).toThrow('has both "loader" and "loaderData"') + }) +}) + +describe('renderInRoute', () => { + test('renders one element in one route with the state the test supplies', async () => { + const app = createApp() + const { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + render, + }) + + const { router } = await renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: '5' }, + search: { tab: 'comments' }, + context: { + locale: 'en', + session: { user: testUser }, + user: testUser, + scope: 'seeded scope', + }, + loaderData: { post: { id: '5', title: 'Seeded post' } }, + routes: { '/_authed': { loaderData: { unreadCount: 4 } } }, + }) + + // The first render is complete: nothing is pending. + 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 { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + render, + }) + const state = { + route: '/_authed/posts/$postId', + params: { postId: '5' }, + context: { + locale: 'en', + session: { user: testUser }, + user: testUser, + scope: 'seeded scope', + }, + loaderData: { post: { id: '5', title: 'Seeded post' } }, + routes: { '/_authed': { loaderData: { unreadCount: 4 } } }, + } as const + + await renderInRoute(, state) + expect(screen.getByText(/on tab details/)).toBeInTheDocument() + cleanup() + + await expect( + renderInRoute(, { + ...state, + search: { tab: 'broken' }, + }), + ).rejects.toThrow('Unknown tab') + }) + + test('takes context and loader data from the defaults of the application', async () => { + const app = createApp() + const { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + render, + defaults: { + context: { + locale: 'en', + session: { user: testUser }, + user: testUser, + scope: 'default scope', + }, + routes: { '/_authed': { loaderData: { unreadCount: 2 } } }, + }, + }) + + await renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: '5' }, + context: { user: realUser }, + loaderData: { post: { id: '5', title: 'Seeded post' } }, + }) + + expect( + screen.getByText( + 'Real user reads post 5 in en on tab details with 2 unread in default scope', + ), + ).toBeInTheDocument() + expect(app.calls).toEqual([]) + }) + + test('navigates with the real router and renders no other route', async () => { + const app = createApp() + const { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + render, + }) + + const { router } = await renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: '5' }, + context: { + locale: 'en', + session: { user: testUser }, + user: testUser, + scope: 'seeded scope', + }, + loaderData: { post: { id: '5', title: 'Seeded post' } }, + routes: { '/_authed': { loaderData: { unreadCount: 4 } } }, + }) + + 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 { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + render, + }) + + await renderInRoute(

In the lazy route

, { + route: '/lazy', + context: { locale: 'en', session: { user: null } }, + }) + + expect(screen.getByText('In the lazy route')).toBeInTheDocument() + expect(app.loadLazyRoute).not.toHaveBeenCalled() + }) + + test('applies the router options of the application, such as Wrap', async () => { + const app = createApp() + const { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + render, + routerOptions: { + Wrap: ({ children }) => ( +
{children}
+ ), + defaultComponent: () =>

Default component

, + }, + }) + + await renderInRoute(

Element

, { + route: '/login', + context: { locale: 'en', session: { user: null } }, + }) + + expect(screen.getByLabelText('Providers')).toHaveTextContent('Element') + expect(screen.queryByText('Default component')).not.toBeInTheDocument() + }) + + test('lets an error of the element reach the test', async () => { + const app = createApp() + const { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + render, + }) + const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) + function Broken(): never { + throw new Error('The element is broken') + } + + await expect( + renderInRoute(, { + route: '/login', + context: { locale: 'en', session: { user: null } }, + }), + ).rejects.toThrow('The element is broken') + + consoleError.mockRestore() + }) + + test('fails when a path param is missing', async () => { + const app = createApp() + const { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + render, + }) + + await expect( + renderInRoute(, { + route: '/_authed/posts/$postId', + // @ts-expect-error `postId` is missing + params: {}, + context: { + locale: 'en', + session: { user: testUser }, + user: testUser, + scope: 'seeded scope', + }, + loaderData: { post: { id: '5', title: 'Seeded post' } }, + routes: { '/_authed': { loaderData: { unreadCount: 4 } } }, + }), + ).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() + const { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + render, + }) + + await expect( + renderInRoute(

Element

, { + route: '/_authed', + context: { + locale: 'en', + session: { user: testUser }, + user: testUser, + }, + loaderData: { unreadCount: 4 }, + }), + ).rejects.toThrow('The route "/_authed" is not matched at "/"') + }) + + test('fails for a route that does not exist', async () => { + const app = createApp() + const { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + render, + }) + + await expect( + renderInRoute(

Element

, { + // @ts-expect-error not a route id of this tree + route: '/missing', + }), + ).rejects.toThrow('The route "/missing" does not exist in the route tree') + }) + + test('needs a render function', async () => { + const app = createApp() + const { renderInRoute } = createRouterTesting({ + routeTree: app.routeTree, + }) + + await expect( + renderInRoute(

Element

, { + route: '/login', + context: { locale: 'en', session: { user: null } }, + }), + ).rejects.toThrow('renderInRoute needs a render function') + }) +}) diff --git a/packages/react-router/vite.config.ts b/packages/react-router/vite.config.ts index 798d9b74e4..22e54b4032 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.tsx', ], 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..ff09029b05 --- /dev/null +++ b/packages/router-core/src/testing/index.ts @@ -0,0 +1,24 @@ +export { + assertIsolatedRouteLoaded, + assertRouteTestParams, + createIsolatedRouteTree, + createTestRouteTree, + initRouteTree, + setTestRouterLocation, +} from './routeTree' +export type { + AnyRouteTestOverride, + AnyRouteTestOverrides, + IsolatedRouteTreeOptions, +} from './routeTree' +export type { + RouteTestBeforeLoadFn, + RouteTestComponents, + RouteTestContextFn, + RouteTestLoaderFn, + RouteTestOptions, + RouteTestOverride, + RouteTestOverrides, + RouterTestingDefaults, + TestRouterContextOption, +} 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..46cc33c997 --- /dev/null +++ b/packages/router-core/src/testing/routeTree.ts @@ -0,0 +1,326 @@ +import { SEGMENT_TYPE_PARAM } from '../new-process-route-tree' +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 + loaderData?: unknown + context?: unknown + component?: unknown + pendingComponent?: unknown + errorComponent?: unknown + notFoundComponent?: unknown +} + +export type AnyRouteTestOverrides = Record< + string, + AnyRouteTestOverride | undefined +> + +const componentOptions = [ + '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. 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 { + if ((routeTree.id as string | undefined) !== undefined) { + return + } + 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 { + initRouteTree(routeTree) + + 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( + patch: RouteOptionsPatch, + routeId: string, + override: AnyRouteTestOverride, +) { + if ('loader' in override && 'loaderData' in override) { + throw new Error( + `The override for route "${routeId}" has both "loader" and "loaderData". Pass one of them.`, + ) + } + if ('loaderData' in override) { + const loaderData = override.loaderData + patch.loader = () => loaderData + } + if ('loader' in override) { + patch.loader = override.loader + } + if ('context' in override) { + const context = override.context + if (typeof context === 'function') { + patch.context = context + } else { + // A seed stands for everything the route contributes to the context, + // so neither of the two options that produce it may run. + patch.context = () => context + patch.beforeLoad = undefined + } + } + if ('beforeLoad' in override) { + patch.beforeLoad = override.beforeLoad + } + for (const key of componentOptions) { + if (key in override) { + patch[key] = override[key] + } + } +} + +/** + * Copies a route tree for one test router and applies per-route overrides. + * Later override maps win over earlier ones, option by option. Routes without + * an override keep the application's options. + */ +export function createTestRouteTree( + routeTree: TRouteTree, + ...overrideMaps: Array +): TRouteTree { + initRouteTree(routeTree) + for (const overrides of overrideMaps) { + if (overrides) { + assertKnownRouteIds(routeTree, Object.keys(overrides)) + } + } + + return cloneRouteTree( + routeTree, + (route) => { + let patch: RouteOptionsPatch | undefined + for (const overrides of overrideMaps) { + const override = overrides?.[route.id] + if (override) { + patch ??= {} + applyOverride(patch, route.id, override) + } + } + return patch + }, + 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: + * the target route is not matched, or a match failed, for example because + * the search params did not pass the route's `validateSearch`. + */ +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 === '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/types.ts b/packages/router-core/src/testing/types.ts new file mode 100644 index 0000000000..d766f1d019 --- /dev/null +++ b/packages/router-core/src/testing/types.ts @@ -0,0 +1,252 @@ +import type { + AnyRoute, + BeforeLoadContextOptions, + ContextAsyncReturnType, + ContextReturnType, + LoaderFnContext, + RouteContextOptions, +} from '../route' +import type { AllContext, RouteById, RouteIds } from '../routeInfo' +import type { InferRouterContext } from '../router' +import type { Awaitable } 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 } + +type OptionalWhenUndefined< + TKey extends PropertyKey, + TValue, +> = undefined extends TValue + ? { [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`: a replacement for that option. + * - `context`: a function replaces the route's `context` option. A value is a + * seed: it stands for everything the route adds to the context, and neither + * the route's `context` option nor its `beforeLoad` runs. + * - `loaderData`: a seed. The route's loader does not run. + * - 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 + loaderData?: TRoute['types']['loaderData'] + context?: TRoute['types']['routeContext'] | RouteTestContextFn +} + +/** Overrides by route id. */ +export type RouteTestOverrides< + TRouteTree extends AnyRoute, + TComponents = RouteTestComponents, +> = { + [TId in RouteIds]?: RouteTestOverride< + RouteById, + TComponents + > +} + +/** + * Defaults an application sets once for all of its route tests. + */ +export interface RouterTestingDefaults< + TRouteTree extends AnyRoute, + TComponents = RouteTestComponents, +> { + /** + * Context values every test router starts with. A key given here becomes + * optional in the `context` of each test. + */ + context?: AllContext + /** + * Overrides every test router starts with. A test's own override for a + * route wins, option by option. An isolated route test takes only the + * `loaderData` seeds from here. + */ + routes?: RouteTestOverrides +} + +type DefaultContextKeys = TDefaults extends { + context: infer TContext +} + ? keyof TContext + : never + +type DefaultLoaderDataIds = TDefaults extends { + routes: infer TRoutes +} + ? { + [TId in keyof TRoutes]: TRoutes[TId] extends { loaderData: any } + ? TId + : never + }[keyof TRoutes] + : never + +/** Makes the keys optional that the application's defaults already provide. */ +type WithDefaults = [TValue] extends [ + void | undefined | null, +] + ? TValue + : [TDefaultKeys & keyof TValue] extends [never] + ? TValue + : Omit & + Partial> + +/** The `context` option of a test router: the router context minus the defaults. */ +export type TestRouterContextOption< + TRouteTree extends AnyRoute, + TDefaults = {}, +> = OptionalWhenEmpty< + 'context', + WithDefaults, DefaultContextKeys> +> + +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 RequiresLoaderData< + TRoute extends AnyRoute, + TDefaults, +> = undefined extends TRoute['types']['loaderData'] + ? false + : TRoute['types']['id'] extends DefaultLoaderDataIds + ? false + : true + +type AncestorLoaderData = { + [TAncestor in AncestorRoutes as RequiresLoaderData< + TAncestor, + TDefaults + > extends true + ? TAncestor['types']['id'] + : never]: { loaderData: TAncestor['types']['loaderData'] } +} & { + [TAncestor in AncestorRoutes as RequiresLoaderData< + TAncestor, + TDefaults + > extends true + ? never + : TAncestor['types']['id']]?: { + loaderData?: TAncestor['types']['loaderData'] + } +} + +type RouteTestStateFor = OptionalWhenEmpty< + 'params', + TRoute['types']['allParams'] +> & + OptionalWhenEmpty<'search', TRoute['types']['fullSearchSchemaInput']> & + OptionalWhenEmpty< + 'context', + WithDefaults> + > & + (TRoute['types']['id'] extends DefaultLoaderDataIds + ? { loaderData?: TRoute['types']['loaderData'] } + : OptionalWhenUndefined<'loaderData', TRoute['types']['loaderData']>) & + OptionalWhenEmpty<'routes', AncestorLoaderData> + +/** + * 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 merged context of the route, minus the defaults. + * - `loaderData`: the route's loader data. + * - `routes`: loader data of the ancestors whose loader returns something. + */ +export type RouteTestOptions< + TRouteTree extends AnyRoute, + TId, + TDefaults = {}, +> = { route: TId } & RouteTestStateFor, TDefaults> diff --git a/packages/router-core/tests/testing.test.ts b/packages/router-core/tests/testing.test.ts new file mode 100644 index 0000000000..d8fe9ac86d --- /dev/null +++ b/packages/router-core/tests/testing.test.ts @@ -0,0 +1,432 @@ +import { describe, expect, test, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { BaseRootRoute, BaseRoute } from '../src' +import { + assertIsolatedRouteLoaded, + assertRouteTestParams, + createIsolatedRouteTree, + createTestRouteTree, + 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', + validateSearch: (search: Record) => { + if (search.tab === 'broken') { + throw new Error('Unknown tab') + } + 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('leaves a tree alone that a router has already processed', () => { + const { routeTree, postRoute } = createTree() + createRouter(routeTree, '/') + const originalIndex = postRoute.originalIndex + const init = vi.spyOn(postRoute, 'init') + + initRouteTree(routeTree) + + expect(init).not.toHaveBeenCalled() + expect(postRoute.originalIndex).toBe(originalIndex) + }) +}) + +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('treats a context value as a seed for everything the route contributes', async () => { + const { routeTree, calls } = createTree() + + const router = createRouter( + createTestRouteTree(routeTree, { + '/layout/posts/$postId': { context: { 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('lets a later override map win, option by option', async () => { + const { routeTree } = createTree() + + const router = createRouter( + createTestRouteTree( + routeTree, + { + '/layout': { loaderData: 'default layout data' }, + '/layout/posts/$postId': { + loader: () => 'default post data', + component: 'default component', + }, + }, + undefined, + { + '/layout/posts/$postId': { loaderData: 'test post data' }, + }, + ), + '/posts/1', + ) + await router.load() + + expect(getMatch(router, '/layout')?.loaderData).toBe('default layout data') + expect(getMatch(router, '/layout/posts/$postId')?.loaderData).toBe( + 'test post data', + ) + expect(router.routesById['/layout/posts/$postId']!.options.component).toBe( + 'default 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 an ambiguous loader override', () => { + 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.', + ) + }) +}) + +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__, /.', + ) + }) +}) 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/pnpm-lock.yaml b/pnpm-lock.yaml index 4328f4fab6..bf4c0bb5df 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': @@ -14922,7 +14959,7 @@ importers: 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) vite-plugin-solid: specifier: ^2.11.10 || ^3.0.0-0 - version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(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)) + version: 2.11.16(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(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)) zod: specifier: 'catalog:' version: 4.5.4 @@ -29037,6 +29074,16 @@ packages: '@testing-library/jest-dom': optional: true + vite-plugin-solid@2.11.16: + resolution: {integrity: sha512-qguFUmqY2ICuoGHrZjm+cWpvKkqVyWDMptipC/BIEGr9q6wEzwTWYOjM9pEWJ+yoTuF6T5OpysI2Okdy7rsVlQ==} + peerDependencies: + '@testing-library/jest-dom': ^5.16.6 || ^5.17.0 || ^6.0.0 || ^7.0.0 + solid-js: 1.9.12 + vite: ^8.3.4 + peerDependenciesMeta: + '@testing-library/jest-dom': + optional: true + vite-tsconfig-paths@6.1.1: resolution: {integrity: sha512-2cihq7zliibCCZ8P9cKJrQBkfgdvcFkOOc3Y02o3GWUDLgqjWsZudaoiuOwO/gzTzy17cS5F7ZPo4bsnS4DGkg==} peerDependencies: @@ -36774,6 +36821,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 +40457,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 +40473,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 +41152,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 @@ -43987,6 +44070,21 @@ snapshots: transitivePeerDependencies: - supports-color + vite-plugin-solid@2.11.16(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(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)): + dependencies: + '@babel/core': 7.29.7(supports-color@10.2.2) + '@types/babel__core': 7.20.5 + babel-preset-solid: 1.9.10(@babel/core@7.29.7(supports-color@10.2.2))(solid-js@1.9.12) + merge-anything: 5.1.7 + solid-js: 1.9.12 + solid-refresh: 0.6.3(solid-js@1.9.12)(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) + 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)) + optionalDependencies: + '@testing-library/jest-dom': 6.6.3 + transitivePeerDependencies: + - supports-color + vite-tsconfig-paths@6.1.1(@typescript/typescript6@6.0.2)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(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: debug: 4.4.3(supports-color@10.2.2) @@ -44200,6 +44298,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 From 070c10a34bacc00f74a5f48b16f7fc97acfb6ffa Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:19:53 +0100 Subject: [PATCH 2/8] docs(router): document the experimental route testing utilities Add a Testing Routes guide for React, a `createRouterTesting` API page, and links to them from the testing how-to guides. Both pages carry an experimental note. Co-Authored-By: Claude Opus 5.5 --- docs/router/api/router.md | 1 + .../api/router/createRouterTestingFunction.md | 163 ++++++++++ docs/router/config.json | 7 +- docs/router/guide/testing-routes.md | 280 ++++++++++++++++++ docs/router/how-to/setup-testing.md | 2 + docs/router/how-to/test-file-based-routing.md | 2 + 6 files changed, 454 insertions(+), 1 deletion(-) create mode 100644 docs/router/api/router/createRouterTestingFunction.md create mode 100644 docs/router/guide/testing-routes.md diff --git a/docs/router/api/router.md b/docs/router/api/router.md index 2c5ede186c..c4716ce554 100644 --- a/docs/router/api/router.md +++ b/docs/router/api/router.md @@ -12,6 +12,7 @@ title: Router API - [`createLazyRoute`](./router/createLazyRouteFunction.md) - [`createRouteMask`](./router/createRouteMaskFunction.md) - [`createRouter`](./router/createRouterFunction.md) + - [`createRouterTesting`](./router/createRouterTestingFunction.md) (experimental, React only) - [`defer`](./router/deferFunction.md) - [`getRouteApi`](./router/getRouteApiFunction.md) - [`isNotFound`](./router/isNotFoundFunction.md) diff --git a/docs/router/api/router/createRouterTestingFunction.md b/docs/router/api/router/createRouterTestingFunction.md new file mode 100644 index 0000000000..07f26ca0f7 --- /dev/null +++ b/docs/router/api/router/createRouterTestingFunction.md @@ -0,0 +1,163 @@ +--- +id: createRouterTestingFunction +title: createRouterTesting function +--- + +> **Experimental:** `createRouterTesting` is experimental and subject to change. It is available for React only. + +The `createRouterTesting` function creates test helpers for an app's route tree, typed from that tree. Import it from `@tanstack/react-router/testing`. The [Testing Routes guide](../../guide/testing-routes.md) shows how to use it. + +## createRouterTesting options + +The `createRouterTesting` function accepts a single object with the following properties. + +### `routeTree` property + +- Type: `AnyRoute` +- Required +- The route tree of the app. Every test router is built from a copy of it, and the helpers are typed from it. + +### `render` property + +- Type: `(ui: React.ReactElement) => unknown` +- Optional +- The render function of your test library, for example `render` from `@testing-library/react`. `renderInRoute` calls it with a `` element and awaits the result. Without it, `renderInRoute` throws. + +### `routerOptions` property + +- Type: [`RouterOptions`](./RouterOptionsType.md) without `routeTree`, `history` and `context` +- Optional +- Options for every test router, for example `Wrap`. `renderInRoute` leaves out `defaultComponent`, `defaultPendingComponent` and `defaultErrorComponent`, and sets `disableGlobalCatchBoundary`. + +### `defaults` property + +- Type: `{ context?: ..., routes?: RouteTestOverrides }` +- Optional +- `context`: values added to the router context of every test router. In `renderInRoute` they are the base of the route's context. Keys given here become optional in the `context` of each test. +- `routes`: [route overrides](#route-overrides) applied to every router that `createTestRouter` creates. A test's own override for a route wins, option by option. `renderInRoute` uses only the `loaderData` seeds, which become optional in each test. + +## createRouterTesting returns + +An object with the `createTestRouter` and `renderInRoute` functions. + +### `createTestRouter` function + +Creates a [`Router`](./RouterType.md) over a copy of the route tree. Every route runs the app's own options unless `routes` replaces them. The router has not loaded yet: render it with `RouterProvider`, or call `router.load()`. + +It accepts an optional object with these properties: + +- `location` + - Type: [`NavigateOptions`](./NavigateOptionsType.md), checked against the route tree + - Optional + - Where the router starts. Defaults to `/`. +- `history` + - Type: `RouterHistory` + - Optional + - A history to start from instead of `location`, for entries that are not valid navigation targets. +- `context` + - Type: the router context of the route tree + - Required when the router context has values that `defaults.context` does not provide +- `routes` + - Type: `RouteTestOverrides` + - Optional + - [Route overrides](#route-overrides) by route id. A route that is not listed keeps the app's options. + +It throws when `routes` names a route that does not exist, or gives a route both `loader` and `loaderData`. + +### `renderInRoute` function + +`renderInRoute(element, options)` renders `element` inside the route `options.route`, with the state the test supplies. 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. + +`options` has these properties: + +- `route` + - Type: a route id of the route tree + - Required + - The route the element renders in. +- `params` + - Type: the path params of the route + - Required when the route has path params +- `search` + - 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` + - Type: the whole context of the route, as `useRouteContext` returns it + - Required when the context has values that `defaults.context` does not provide +- `loaderData` + - Type: the loader data of the route + - Required when the route's loader returns data and `defaults.routes` has no seed for it +- `routes` + - Type: `{ [routeId]: { loaderData } }` for the routes above `route` + - Required when one of those routes has a loader that returns data and no seed in `defaults.routes` + +It returns a promise of `{ router, result }`. `router` is the test router, which has loaded before the element renders. `result` is what `render` returned, awaited. + +The promise rejects when no `render` function was given, 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 `validateSearch` rejects the search params), and when the location of `route` does not lead to it, as for a pathless layout route. + +## Route overrides + +An override for one route id. Every property is typed from that route. + +| 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, or its value | A function replaces the route's `context` option. A value is a seed: neither `context` nor `beforeLoad` of the route runs. | +| `loaderData` | The route's loader data | A seed: the loader is replaced by one that returns it. | +| `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. + +## Types + +`@tanstack/react-router/testing` also exports these types: + +- `RouteTestOverrides`: overrides by route id, for example to check a shared override object with `satisfies`. +- `RouterTestingDefaults`: the shape of `defaults`. +- `RenderInRouteOptions`: the options of `renderInRoute` for one route. +- `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. Framework packages build on it; apps use `@tanstack/react-router/testing`. + +| Export | What it does | +| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `createTestRouteTree(routeTree, ...overrideMaps)` | Copies a route tree and applies override maps. A later map wins, option by option. | +| `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 } from '@testing-library/react' +import { RouterProvider } from '@tanstack/react-router' +import { createRouterTesting } from '@tanstack/react-router/testing' +import { routeTree } from './routeTree.gen' + +const { createTestRouter, renderInRoute } = createRouterTesting({ + routeTree, + render, +}) + +// The app's lifecycle runs, except for the root route's beforeLoad. +const router = createTestRouter({ + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'en' }, + routes: { __root__: { context: { session: { user: null } } } }, +}) +render() + +// No lifecycle runs. The types require the state PostHeader can read. +await renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: '1' }, + context: { locale: 'en', session: { user: ada }, user: ada }, + loaderData: { post }, + routes: { '/_authed': { loaderData: { unreadCount: 0 } } }, +}) +``` diff --git a/docs/router/config.json b/docs/router/config.json index 1258ddd817..501eb94b64 100644 --- a/docs/router/config.json +++ b/docs/router/config.json @@ -300,7 +300,12 @@ "frameworks": [ { "label": "react", - "children": [] + "children": [ + { + "label": "Testing Routes", + "to": "guide/testing-routes" + } + ] }, { "label": "solid", diff --git a/docs/router/guide/testing-routes.md b/docs/router/guide/testing-routes.md new file mode 100644 index 0000000000..95507eb87e --- /dev/null +++ b/docs/router/guide/testing-routes.md @@ -0,0 +1,280 @@ +--- +id: testing-routes +title: Testing Routes +--- + +> **Experimental:** The route testing utilities are experimental and subject to change. They are available for React only. + +`@tanstack/react-router/testing` builds test routers from your app's route tree. 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. + +It has two helpers: + +| Helper | 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 | +| `renderInRoute` | A component that reads route state: params, search, context, loaders | None of them. The test supplies the state the component reads, and the TypeScript types require it all | + +## Setup + +Both helpers 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', + }, +}) +``` + +With code-based routing, pass the route tree you build with `addChildren`. + +Create the helpers once, in a file your tests import: + +```tsx title="src/test-utils.tsx" +import { render } from '@testing-library/react' +import { createRouterTesting } from '@tanstack/react-router/testing' +import { routeTree } from './routeTree.gen' + +export const { createTestRouter, renderInRoute } = createRouterTesting({ + routeTree, + render, +}) +``` + +`render` is the function your test library uses to mount a React element. Only `renderInRoute` calls it; TanStack Router does not depend on a test library. + +## 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` creates a router over a copy of your route tree. 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 } from '@tanstack/react-router' +import { expect, test } from 'vitest' +import { createTestRouter } from '../src/test-utils' + +test('sends a signed-out visitor to the login page', async () => { + const router = createTestRouter({ + location: { to: '/posts/$postId', params: { postId: '1' } }, + context: { locale: 'en' }, + routes: { + // The root route's beforeLoad does not run. This is its result. + __root__: { context: { 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. Without `location`, the router starts at `/`. To start from history entries that are not valid navigation targets, pass `history: createMemoryHistory({ initialEntries: [...] })` instead. +- `context` is the router context, typed from your root route. +- 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 + +`routes` takes overrides by route id. Each override is typed from the route it replaces: + +| Override | Effect | +| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `beforeLoad: fn` | Replaces the route's `beforeLoad`. `fn` receives what the original receives and has to return what the original returns. | +| `loader: fn` | Replaces the route's loader. `fn` receives what the original receives and has to return the route's loader data. | +| `context: fn` | Replaces the route's `context` option. | +| `context: value` | A seed: `value` is everything the route adds to the context. Neither the route's `context` option nor its `beforeLoad` runs. | +| `loaderData: value` | A seed: the route's loader is replaced by one that returns `value`. | +| `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, and a route cannot take both `loader` and `loaderData`. 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({ + location: { to: '/posts/$postId', params: { postId: '7' } }, + context: { locale: 'en' }, + routes: { + __root__: { context: { 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`: + +```tsx +import type { RouteTestOverrides } from '@tanstack/react-router/testing' +import type { routeTree } from '../src/routeTree.gen' + +export const signedIn = { + __root__: { context: { session: { user: ada } } }, +} satisfies RouteTestOverrides +``` + +## Test a component with `renderInRoute` + +`renderInRoute` 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 { screen } from '@testing-library/react' +import { expect, test } from 'vitest' +import { PostHeader } from '../src/components/PostHeader' +import { renderInRoute } from '../src/test-utils' + +test('marks posts written by the signed-in user', async () => { + await renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: '1' }, + context: { locale: 'en', session: { user: ada }, user: ada }, + loaderData: { post: createPost({ authorId: ada.id }) }, + routes: { '/_authed': { loaderData: { unreadCount: 0 } } }, + }) + + expect(screen.getByText('Written by you')).toBeTruthy() +}) +``` + +No `context`, `beforeLoad` or `loader` option of any route runs, none of your route components render, and lazy routes are not loaded. Nothing of the app runs around the element. The router has loaded before the element renders, so the first render is complete when `renderInRoute` resolves. + +`renderInRoute` resolves to `{ router, result }`. `router` is a real router: links get their real `href`, and navigation updates `router.state`, but every route other than the one under test renders nothing. `result` is what your `render` function returned. + +### 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` | The route's loader data | The route's loader returns data | +| `routes` | `{ [routeId]: { loaderData } }` for the routes above it | One of those routes has a loader that returns data | + +In the example, `context` has to hold `locale` from the router context, `session` from the root route and `user` from `/_authed`, and `routes` has to hold the loader data of `/_authed`. Leaving any of them out is a type error that names the missing value. + +> [!NOTE] +> Type errors appear in your editor and when you type-check your tests, for example with `tsc --noEmit`. `vitest run` strips types without checking them: a test that leaves state out still runs, and the component reads `undefined`. Type-check your test files in CI. + +At run time, `renderInRoute` fails 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, +- 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 values across tests + +Put values that many tests share into `defaults`. What the defaults provide becomes optional in each test: + +```tsx title="src/test-utils.tsx" +export const { createTestRouter, renderInRoute } = createRouterTesting({ + routeTree, + render, + defaults: { + context: { locale: 'en', session: { user: ada }, user: ada }, + routes: { '/_authed': { loaderData: { unreadCount: 0 } } }, + }, +}) +``` + +```tsx +await renderInRoute(, { + route: '/_authed/posts/$postId', + params: { postId: '1' }, + loaderData: { post: createPost() }, +}) +``` + +- `defaults.context` is added to the router context of every test router, and is the base of the route's context in `renderInRoute`. A test's own `context` wins, key by key. In `createTestRouter` it does not stop a route's `beforeLoad` from running; seed the route in `defaults.routes` for that. +- `defaults.routes` applies to every router that `createTestRouter` creates, and a test's own override for a route wins, option by option. `renderInRoute` uses only the `loaderData` seeds from it. + +## Providers and router options + +`routerOptions` are passed to every test router, for example `Wrap` for the providers your components need: + +```tsx title="src/test-utils.tsx" +export const { createTestRouter, renderInRoute } = createRouterTesting({ + routeTree, + render, + routerOptions: { + Wrap: ({ children }) => ( + {children} + ), + }, +}) +``` + +`renderInRoute` keeps them, except `defaultComponent`, `defaultPendingComponent` and `defaultErrorComponent`. It also turns off the router's global error boundary, so an error the element throws reaches the test. + +## Limitations + +- Only React is supported. +- 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 [`createRouterTesting` reference](../api/router/createRouterTestingFunction.md). 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 From a39b8635c16ef3abb9e2df67b61c86c44091be41 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:29:19 +0100 Subject: [PATCH 3/8] docs(router): type-check route tests with Vitest Vitest can type-check tests: with `typecheck.enabled` it runs `tsc` with the project's tsconfig, and a type error in a test file fails the run. Enable it in the setup example and say so instead of claiming that `vitest run` never checks types. Co-Authored-By: Claude Opus 5.5 --- docs/router/guide/testing-routes.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/router/guide/testing-routes.md b/docs/router/guide/testing-routes.md index 95507eb87e..5d54ca1a37 100644 --- a/docs/router/guide/testing-routes.md +++ b/docs/router/guide/testing-routes.md @@ -30,6 +30,8 @@ export default defineConfig({ ], test: { environment: 'jsdom', + // Type-check the tests, so that a test that leaves out route state fails. + typecheck: { enabled: true }, }, }) ``` @@ -215,7 +217,7 @@ The options are typed from the route that `route` names. They ask for what the s In the example, `context` has to hold `locale` from the router context, `session` from the root route and `user` from `/_authed`, and `routes` has to hold the loader data of `/_authed`. Leaving any of them out is a type error that names the missing value. > [!NOTE] -> Type errors appear in your editor and when you type-check your tests, for example with `tsc --noEmit`. `vitest run` strips types without checking them: a test that leaves state out still runs, and the component reads `undefined`. Type-check your test files in CI. +> 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, `renderInRoute` fails with a message when: From c85dc116286b83a3a883ea108bc23b750e7b159a Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:58:36 +0100 Subject: [PATCH 4/8] feat(react-router): split route testing into two standalone functions Drop the `createRouterTesting` factory and its injected `render`: - `createTestRouter` takes the options of `createRouter`, plus `location` and `overrides`, and returns a router that has not loaded. - `createIsolatedTestRouter` resolves to a loaded router that renders one element in one route. Its `loaderData` is one map by route id for the route and the routes above it. Override keys named after route options (`beforeLoad`, `loader`, `context`, components) now only take functions with the original's signature; seeds are `loaderData` and `routeContext`. The root route is addressed with `rootRouteId`, which `IsolatedRouteState` checks with `ConstrainLiteral` so that TypeScript keeps its literal type. Co-Authored-By: Claude Opus 5.5 --- .changeset/router-testing-utilities.md | 6 +- docs/router/api/router.md | 3 +- .../createIsolatedTestRouterFunction.md | 92 +++++ .../api/router/createRouterTestingFunction.md | 163 -------- .../api/router/createTestRouterFunction.md | 101 +++++ docs/router/guide/testing-routes.md | 192 +++++----- .../route-testing/src/test-fixtures.ts | 20 + .../route-testing/src/test-utils.tsx | 41 -- .../route-testing/tests/post-header.test.tsx | 97 +++-- .../route-testing/tests/post-route.test.tsx | 46 ++- .../tests/route-testing.test-d.tsx | 86 +++-- .../route-testing/tests/user-menu.test.tsx | 38 +- packages/react-router/src/testing.ts | 260 +++++++++++++ packages/react-router/src/testing.tsx | 359 ------------------ .../react-router/tests/testing.test-d.tsx | 282 +++++++------- packages/react-router/tests/testing.test.tsx | 352 +++++++---------- packages/react-router/vite.config.ts | 2 +- packages/router-core/src/testing/index.ts | 4 +- packages/router-core/src/testing/routeTree.ts | 89 ++--- packages/router-core/src/testing/types.ts | 150 ++------ packages/router-core/tests/testing.test.ts | 62 +-- 21 files changed, 1128 insertions(+), 1317 deletions(-) create mode 100644 docs/router/api/router/createIsolatedTestRouterFunction.md delete mode 100644 docs/router/api/router/createRouterTestingFunction.md create mode 100644 docs/router/api/router/createTestRouterFunction.md create mode 100644 e2e/react-router/route-testing/src/test-fixtures.ts delete mode 100644 e2e/react-router/route-testing/src/test-utils.tsx create mode 100644 packages/react-router/src/testing.ts delete mode 100644 packages/react-router/src/testing.tsx diff --git a/.changeset/router-testing-utilities.md b/.changeset/router-testing-utilities.md index cf0508357e..fa9d9a4e57 100644 --- a/.changeset/router-testing-utilities.md +++ b/.changeset/router-testing-utilities.md @@ -3,8 +3,10 @@ '@tanstack/react-router': minor --- -Add typed test utilities for routes, exported from `@tanstack/react-router/testing`. +Add experimental, typed test utilities for routes, exported from `@tanstack/react-router/testing`. Both return a router to render with `RouterProvider`. -`createRouterTesting({ routeTree })` returns two helpers. `createTestRouter` creates a router over a copy of the app's route tree: every route runs the app's own lifecycle unless the test replaces `context`, `beforeLoad`, `loader` or a component option for that route id, or seeds its context or loader data. `renderInRoute` 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. +`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 framework-independent part is exported from `@tanstack/router-core/testing`. diff --git a/docs/router/api/router.md b/docs/router/api/router.md index c4716ce554..190fed35db 100644 --- a/docs/router/api/router.md +++ b/docs/router/api/router.md @@ -12,7 +12,8 @@ title: Router API - [`createLazyRoute`](./router/createLazyRouteFunction.md) - [`createRouteMask`](./router/createRouteMaskFunction.md) - [`createRouter`](./router/createRouterFunction.md) - - [`createRouterTesting`](./router/createRouterTestingFunction.md) (experimental, React only) + - [`createTestRouter`](./router/createTestRouterFunction.md) (experimental, React only) + - [`createIsolatedTestRouter`](./router/createIsolatedTestRouterFunction.md) (experimental, React only) - [`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..04b9003f30 --- /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 only. + +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 `@tanstack/react-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` and `search`. It leaves out `defaultComponent`, `defaultPendingComponent` and `defaultErrorComponent`, 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.ReactElement` +- 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 `validateSearch` rejects the search params), 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/createRouterTestingFunction.md b/docs/router/api/router/createRouterTestingFunction.md deleted file mode 100644 index 07f26ca0f7..0000000000 --- a/docs/router/api/router/createRouterTestingFunction.md +++ /dev/null @@ -1,163 +0,0 @@ ---- -id: createRouterTestingFunction -title: createRouterTesting function ---- - -> **Experimental:** `createRouterTesting` is experimental and subject to change. It is available for React only. - -The `createRouterTesting` function creates test helpers for an app's route tree, typed from that tree. Import it from `@tanstack/react-router/testing`. The [Testing Routes guide](../../guide/testing-routes.md) shows how to use it. - -## createRouterTesting options - -The `createRouterTesting` function accepts a single object with the following properties. - -### `routeTree` property - -- Type: `AnyRoute` -- Required -- The route tree of the app. Every test router is built from a copy of it, and the helpers are typed from it. - -### `render` property - -- Type: `(ui: React.ReactElement) => unknown` -- Optional -- The render function of your test library, for example `render` from `@testing-library/react`. `renderInRoute` calls it with a `` element and awaits the result. Without it, `renderInRoute` throws. - -### `routerOptions` property - -- Type: [`RouterOptions`](./RouterOptionsType.md) without `routeTree`, `history` and `context` -- Optional -- Options for every test router, for example `Wrap`. `renderInRoute` leaves out `defaultComponent`, `defaultPendingComponent` and `defaultErrorComponent`, and sets `disableGlobalCatchBoundary`. - -### `defaults` property - -- Type: `{ context?: ..., routes?: RouteTestOverrides }` -- Optional -- `context`: values added to the router context of every test router. In `renderInRoute` they are the base of the route's context. Keys given here become optional in the `context` of each test. -- `routes`: [route overrides](#route-overrides) applied to every router that `createTestRouter` creates. A test's own override for a route wins, option by option. `renderInRoute` uses only the `loaderData` seeds, which become optional in each test. - -## createRouterTesting returns - -An object with the `createTestRouter` and `renderInRoute` functions. - -### `createTestRouter` function - -Creates a [`Router`](./RouterType.md) over a copy of the route tree. Every route runs the app's own options unless `routes` replaces them. The router has not loaded yet: render it with `RouterProvider`, or call `router.load()`. - -It accepts an optional object with these properties: - -- `location` - - Type: [`NavigateOptions`](./NavigateOptionsType.md), checked against the route tree - - Optional - - Where the router starts. Defaults to `/`. -- `history` - - Type: `RouterHistory` - - Optional - - A history to start from instead of `location`, for entries that are not valid navigation targets. -- `context` - - Type: the router context of the route tree - - Required when the router context has values that `defaults.context` does not provide -- `routes` - - Type: `RouteTestOverrides` - - Optional - - [Route overrides](#route-overrides) by route id. A route that is not listed keeps the app's options. - -It throws when `routes` names a route that does not exist, or gives a route both `loader` and `loaderData`. - -### `renderInRoute` function - -`renderInRoute(element, options)` renders `element` inside the route `options.route`, with the state the test supplies. 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. - -`options` has these properties: - -- `route` - - Type: a route id of the route tree - - Required - - The route the element renders in. -- `params` - - Type: the path params of the route - - Required when the route has path params -- `search` - - 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` - - Type: the whole context of the route, as `useRouteContext` returns it - - Required when the context has values that `defaults.context` does not provide -- `loaderData` - - Type: the loader data of the route - - Required when the route's loader returns data and `defaults.routes` has no seed for it -- `routes` - - Type: `{ [routeId]: { loaderData } }` for the routes above `route` - - Required when one of those routes has a loader that returns data and no seed in `defaults.routes` - -It returns a promise of `{ router, result }`. `router` is the test router, which has loaded before the element renders. `result` is what `render` returned, awaited. - -The promise rejects when no `render` function was given, 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 `validateSearch` rejects the search params), and when the location of `route` does not lead to it, as for a pathless layout route. - -## Route overrides - -An override for one route id. Every property is typed from that route. - -| 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, or its value | A function replaces the route's `context` option. A value is a seed: neither `context` nor `beforeLoad` of the route runs. | -| `loaderData` | The route's loader data | A seed: the loader is replaced by one that returns it. | -| `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. - -## Types - -`@tanstack/react-router/testing` also exports these types: - -- `RouteTestOverrides`: overrides by route id, for example to check a shared override object with `satisfies`. -- `RouterTestingDefaults`: the shape of `defaults`. -- `RenderInRouteOptions`: the options of `renderInRoute` for one route. -- `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. Framework packages build on it; apps use `@tanstack/react-router/testing`. - -| Export | What it does | -| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `createTestRouteTree(routeTree, ...overrideMaps)` | Copies a route tree and applies override maps. A later map wins, option by option. | -| `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 } from '@testing-library/react' -import { RouterProvider } from '@tanstack/react-router' -import { createRouterTesting } from '@tanstack/react-router/testing' -import { routeTree } from './routeTree.gen' - -const { createTestRouter, renderInRoute } = createRouterTesting({ - routeTree, - render, -}) - -// The app's lifecycle runs, except for the root route's beforeLoad. -const router = createTestRouter({ - location: { to: '/posts/$postId', params: { postId: '1' } }, - context: { locale: 'en' }, - routes: { __root__: { context: { session: { user: null } } } }, -}) -render() - -// No lifecycle runs. The types require the state PostHeader can read. -await renderInRoute(, { - route: '/_authed/posts/$postId', - params: { postId: '1' }, - context: { locale: 'en', session: { user: ada }, user: ada }, - loaderData: { post }, - routes: { '/_authed': { loaderData: { unreadCount: 0 } } }, -}) -``` diff --git a/docs/router/api/router/createTestRouterFunction.md b/docs/router/api/router/createTestRouterFunction.md new file mode 100644 index 0000000000..5e143a2615 --- /dev/null +++ b/docs/router/api/router/createTestRouterFunction.md @@ -0,0 +1,101 @@ +--- +id: createTestRouterFunction +title: createTestRouter function +--- + +> **Experimental:** `createTestRouter` is experimental and subject to change. It is available for React only. + +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 `@tanstack/react-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. + +### `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. Defaults to `/`. + +### `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. Framework packages build on it; apps use `@tanstack/react-router/testing`. + +| Export | What it does | +| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `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/guide/testing-routes.md b/docs/router/guide/testing-routes.md index 5d54ca1a37..71e4dc9aff 100644 --- a/docs/router/guide/testing-routes.md +++ b/docs/router/guide/testing-routes.md @@ -5,18 +5,18 @@ title: Testing Routes > **Experimental:** The route testing utilities are experimental and subject to change. They are available for React only. -`@tanstack/react-router/testing` builds test routers from your app's route tree. 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. +`@tanstack/react-router/testing` creates routers for tests from your app's route tree. 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. -It has two helpers: +It has two functions. Both return a router that you render with `RouterProvider`, so they work with any test library: -| Helper | 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 | -| `renderInRoute` | A component that reads route state: params, search, context, loaders | None of them. The test supplies the state the component reads, and the TypeScript types require it all | +| 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 helpers 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: +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' @@ -38,21 +38,6 @@ export default defineConfig({ With code-based routing, pass the route tree you build with `addChildren`. -Create the helpers once, in a file your tests import: - -```tsx title="src/test-utils.tsx" -import { render } from '@testing-library/react' -import { createRouterTesting } from '@tanstack/react-router/testing' -import { routeTree } from './routeTree.gen' - -export const { createTestRouter, renderInRoute } = createRouterTesting({ - routeTree, - render, -}) -``` - -`render` is the function your test library uses to mount a React element. Only `renderInRoute` calls it; TanStack Router does not depend on a test library. - ## The example app The examples on this page use this app, which also has a `/login` route: @@ -102,21 +87,23 @@ export function PostHeader() { ## Test a route with `createTestRouter` -`createTestRouter` creates a router over a copy of your route tree. Every route behaves as in the app unless the test replaces part of it: +`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 } from '@tanstack/react-router' +import { RouterProvider, rootRouteId } from '@tanstack/react-router' +import { createTestRouter } from '@tanstack/react-router/testing' import { expect, test } from 'vitest' -import { createTestRouter } from '../src/test-utils' +import { routeTree } from '../src/routeTree.gen' test('sends a signed-out visitor to the login page', async () => { const router = createTestRouter({ - location: { to: '/posts/$postId', params: { postId: '1' } }, + routeTree, context: { locale: 'en' }, - routes: { + location: { to: '/posts/$postId', params: { postId: '1' } }, + overrides: { // The root route's beforeLoad does not run. This is its result. - __root__: { context: { session: { user: null } } }, + [rootRouteId]: { routeContext: { session: { user: null } } }, }, }) render() @@ -128,32 +115,32 @@ test('sends a signed-out visitor to the login page', async () => { 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. Without `location`, the router starts at `/`. To start from history entries that are not valid navigation targets, pass `history: createMemoryHistory({ initialEntries: [...] })` instead. -- `context` is the router context, typed from your root route. +- `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 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 -`routes` takes overrides by route id. Each override is typed from the route it replaces: +`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: fn` | Replaces the route's `beforeLoad`. `fn` receives what the original receives and has to return what the original returns. | -| `loader: fn` | Replaces the route's loader. `fn` receives what the original receives and has to return the route's loader data. | -| `context: fn` | Replaces the route's `context` option. | -| `context: value` | A seed: `value` is everything the route adds to the context. Neither the route's `context` option nor its `beforeLoad` runs. | -| `loaderData: value` | A seed: the route's loader is replaced by one that returns `value`. | -| `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. | +| 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, and a route cannot take both `loader` and `loaderData`. 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. +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({ - location: { to: '/posts/$postId', params: { postId: '7' } }, + routeTree, context: { locale: 'en' }, - routes: { - __root__: { context: { session: { user: ada } } }, + 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 }) }), @@ -164,111 +151,120 @@ const router = createTestRouter({ 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`: +To reuse overrides in several tests, check them against `RouteTestOverrides` and spread them: -```tsx +```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 = { - __root__: { context: { session: { user: ada } } }, + [rootRouteId]: { routeContext: { session: { user: ada } } }, } satisfies RouteTestOverrides ``` -## Test a component with `renderInRoute` +```tsx +overrides: { ...signedIn, '/_authed': { loaderData: { unreadCount: 3 } } }, +``` -`renderInRoute` renders one element inside one route. The test supplies the state the route would have in the app: +## 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 { screen } from '@testing-library/react' +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 { renderInRoute } from '../src/test-utils' +import { routeTree } from '../src/routeTree.gen' test('marks posts written by the signed-in user', async () => { - await renderInRoute(, { + const router = await createIsolatedTestRouter({ + routeTree, route: '/_authed/posts/$postId', + element: , params: { postId: '1' }, context: { locale: 'en', session: { user: ada }, user: ada }, - loaderData: { post: createPost({ authorId: ada.id }) }, - routes: { '/_authed': { loaderData: { unreadCount: 0 } } }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost({ authorId: ada.id }) }, + }, }) + render() expect(screen.getByText('Written by you')).toBeTruthy() }) ``` -No `context`, `beforeLoad` or `loader` option of any route runs, none of your route components render, and lazy routes are not loaded. Nothing of the app runs around the element. The router has loaded before the element renders, so the first render is complete when `renderInRoute` resolves. +`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. -`renderInRoute` resolves to `{ router, result }`. `router` is a real router: links get their real `href`, and navigation updates `router.state`, but every route other than the one under test renders nothing. `result` is what your `render` function returned. +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` | The route's loader data | The route's loader returns data | -| `routes` | `{ [routeId]: { loaderData } }` for the routes above it | One of those routes has a loader that returns data | +| 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 `routes` has to hold the loader data of `/_authed`. Leaving any of them out is a type error that names the missing value. +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, `renderInRoute` fails with a message when: +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, - 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 values across tests +## Share state across tests -Put values that many tests share into `defaults`. What the defaults provide becomes optional in each test: +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="src/test-utils.tsx" -export const { createTestRouter, renderInRoute } = createRouterTesting({ - routeTree, - render, - defaults: { - context: { locale: 'en', session: { user: ada }, user: ada }, - routes: { '/_authed': { loaderData: { unreadCount: 0 } } }, - }, -}) +```tsx title="tests/fixtures.ts" +export const signedInContext = { + locale: 'en', + session: { user: ada }, + user: ada, +} ``` ```tsx -await renderInRoute(, { - route: '/_authed/posts/$postId', - params: { postId: '1' }, - loaderData: { post: createPost() }, -}) -``` - -- `defaults.context` is added to the router context of every test router, and is the base of the route's context in `renderInRoute`. A test's own `context` wins, key by key. In `createTestRouter` it does not stop a route's `beforeLoad` from running; seed the route in `defaults.routes` for that. -- `defaults.routes` applies to every router that `createTestRouter` creates, and a test's own override for a route wins, option by option. `renderInRoute` uses only the `loaderData` seeds from it. - -## Providers and router options - -`routerOptions` are passed to every test router, for example `Wrap` for the providers your components need: - -```tsx title="src/test-utils.tsx" -export const { createTestRouter, renderInRoute } = createRouterTesting({ +const router = await createIsolatedTestRouter({ routeTree, - render, - routerOptions: { - Wrap: ({ children }) => ( - {children} - ), + route: '/_authed/posts/$postId', + element: , + params: { postId: '1' }, + context: { ...signedInContext, user: grace }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, }, }) ``` -`renderInRoute` keeps them, except `defaultComponent`, `defaultPendingComponent` and `defaultErrorComponent`. It also turns off the router's global error boundary, so an error the element throws reaches the test. +## 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} + ), +}) +``` + +`createIsolatedTestRouter` leaves out `defaultComponent`, `defaultPendingComponent` and `defaultErrorComponent`, and turns off the router's global error boundary, so an error the element throws reaches the test from your `render` call. 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. ## Limitations @@ -279,4 +275,4 @@ export const { createTestRouter, renderInRoute } = createRouterTesting({ ## API -See the [`createRouterTesting` reference](../api/router/createRouterTestingFunction.md). +See the [`createTestRouter`](../api/router/createTestRouterFunction.md) and [`createIsolatedTestRouter`](../api/router/createIsolatedTestRouterFunction.md) references. 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/src/test-utils.tsx b/e2e/react-router/route-testing/src/test-utils.tsx deleted file mode 100644 index d0ed65a186..0000000000 --- a/e2e/react-router/route-testing/src/test-utils.tsx +++ /dev/null @@ -1,41 +0,0 @@ -import { render } from '@testing-library/react' -import { createRouterTesting } from '@tanstack/react-router/testing' -import { routeTree } from './routeTree.gen' -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, - } -} - -/** - * Test helpers without defaults. Every test supplies the whole state its - * route promises. - */ -export const routerTesting = createRouterTesting({ routeTree, render }) - -/** - * Test helpers with the values most tests of this app share. What is given - * here is optional in each test. - */ -export const appTesting = createRouterTesting({ - routeTree, - render, - defaults: { - context: { - locale: 'en', - session: { user: testUser }, - user: testUser, - }, - routes: { - '/_authed': { loaderData: { unreadCount: 0 } }, - }, - }, -}) diff --git a/e2e/react-router/route-testing/tests/post-header.test.tsx b/e2e/react-router/route-testing/tests/post-header.test.tsx index 8d71e97de4..27323f35ff 100644 --- a/e2e/react-router/route-testing/tests/post-header.test.tsx +++ b/e2e/react-router/route-testing/tests/post-header.test.tsx @@ -1,27 +1,31 @@ -import { fireEvent, screen, waitFor } from '@testing-library/react' +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 { - appTesting, - createPost, - routerTesting, - testUser, -} from '../src/test-utils' +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 fetchMock = vi.fn() - vi.stubGlobal('fetch', fetchMock) - - await routerTesting.renderInRoute(, { - route: '/_authed/posts/$postId', - params: { postId: 'post-1' }, - context: { locale: 'en', session: { user: testUser }, user: testUser }, + const router = await createIsolatedTestRouter({ + ...postRoute, loaderData: { - post: createPost({ title: 'Typed tests', authorId: testUser.id }), + '/_authed': { unreadCount: 2 }, + '/_authed/posts/$postId': { + post: createPost({ title: 'Typed tests', authorId: testUser.id }), + }, }, - routes: { '/_authed': { loaderData: { unreadCount: 2 } } }, }) + render() expect(screen.getByRole('heading').textContent).toBe('Typed tests') expect(screen.getByText('Written by you')).toBeTruthy() @@ -35,13 +39,14 @@ describe('a component rendered in its route with supplied state', () => { const fetchMock = vi.fn() vi.stubGlobal('fetch', fetchMock) - await routerTesting.renderInRoute(, { - route: '/_authed/posts/$postId', - params: { postId: 'post-1' }, - context: { locale: 'en', session: { user: testUser }, user: testUser }, - loaderData: { post: createPost() }, - routes: { '/_authed': { loaderData: { unreadCount: 2 } } }, + const router = await createIsolatedTestRouter({ + ...postRoute, + loaderData: { + '/_authed': { unreadCount: 2 }, + '/_authed/posts/$postId': { post: createPost() }, + }, }) + render() expect(fetchMock).not.toHaveBeenCalled() expect(screen.queryByRole('navigation')).toBeNull() @@ -49,45 +54,57 @@ describe('a component rendered in its route with supplied state', () => { expect(screen.queryByLabelText('Tab content')).toBeNull() }) - test('takes shared values from the defaults of the application', async () => { - await appTesting.renderInRoute(, { - route: '/_authed/posts/$postId', - params: { postId: 'post-1' }, - loaderData: { post: createPost({ status: 'draft' }) }, + 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.queryByText('Written by you')).toBeNull() + expect(screen.getByText('Written by you')).toBeTruthy() }) test('sends search params through the validateSearch of the route', async () => { - await appTesting.renderInRoute(, { - route: '/_authed/posts/$postId', - params: { postId: 'post-1' }, + const router = await createIsolatedTestRouter({ + ...postRoute, search: { tab: 'comments' }, - loaderData: { post: createPost() }, + 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( - appTesting.renderInRoute(, { - route: '/_authed/posts/$postId', - params: { postId: 'post-1' }, + createIsolatedTestRouter({ + ...postRoute, search: { tab: 'history' }, - loaderData: { post: createPost() }, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, }), ).rejects.toThrow('Unknown tab "history"') }) test('navigates with the real router', async () => { - const { router } = await appTesting.renderInRoute(, { - route: '/_authed/posts/$postId', - params: { postId: 'post-1' }, - loaderData: { post: createPost() }, + const router = await createIsolatedTestRouter({ + ...postRoute, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, }) + render() fireEvent.click(screen.getByRole('link', { name: 'Show comments' })) diff --git a/e2e/react-router/route-testing/tests/post-route.test.tsx b/e2e/react-router/route-testing/tests/post-route.test.tsx index f4fd68495c..b16a1aa030 100644 --- a/e2e/react-router/route-testing/tests/post-route.test.tsx +++ b/e2e/react-router/route-testing/tests/post-route.test.tsx @@ -1,7 +1,9 @@ import { render, screen, waitFor } from '@testing-library/react' -import { RouterProvider } from '@tanstack/react-router' +import { RouterProvider, rootRouteId } from '@tanstack/react-router' +import { createTestRouter } from '@tanstack/react-router/testing' import { describe, expect, test, vi } from 'vitest' -import { createPost, routerTesting, testUser } from '../src/test-utils' +import { routeTree } from '../src/routeTree.gen' +import { createPost, testUser } from '../src/test-fixtures' import type { Session } from '../src/api' function stubApi(responses: Record) { @@ -25,9 +27,10 @@ describe('a test router over the route tree of the application', () => { '/api/posts/post-1': createPost({ title: 'From the API' }), }) - const router = routerTesting.createTestRouter({ - location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + const router = createTestRouter({ + routeTree, context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, }) render() @@ -47,13 +50,14 @@ describe('a test router over the route tree of the application', () => { test('follows the redirect of a real beforeLoad', async () => { stubApi({ '/api/session': { user: null } satisfies Session }) - const router = routerTesting.createTestRouter({ + const router = createTestRouter({ + routeTree, + context: { locale: 'en' }, location: { to: '/posts/$postId', params: { postId: 'post-1' }, search: { tab: 'comments' }, }, - context: { locale: 'en' }, }) render() @@ -67,12 +71,13 @@ describe('a test router over the route tree of the application', () => { test('replaces only the lifecycle options a test names', async () => { const fetchMock = stubApi({}) - const router = routerTesting.createTestRouter({ - location: { to: '/posts/$postId', params: { postId: 'post-7' } }, + const router = createTestRouter({ + routeTree, context: { locale: 'en' }, - routes: { + location: { to: '/posts/$postId', params: { postId: 'post-7' } }, + overrides: { // A seed: the session lookup of the root route does not run. - __root__: { context: { session: { user: testUser } } }, + [rootRouteId]: { routeContext: { session: { user: testUser } } }, // A seed for the loader data. '/_authed': { loaderData: { unreadCount: 5 } }, // A replacement, typed like the loader of the route. @@ -102,10 +107,11 @@ describe('a test router over the route tree of the application', () => { '/api/notifications/unread-count': 0, }) - const router = routerTesting.createTestRouter({ - location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + const router = createTestRouter({ + routeTree, context: { locale: 'en' }, - routes: { + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + overrides: { '/_authed/posts/$postId': { loaderData: { post: createPost() }, component: () =>

Replaced page

, @@ -119,11 +125,12 @@ describe('a test router over the route tree of the application', () => { }) test('keeps overrides out of the next router', async () => { - const first = routerTesting.createTestRouter({ - location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + const first = createTestRouter({ + routeTree, context: { locale: 'en' }, - routes: { - __root__: { context: { session: { user: testUser } } }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: testUser } } }, '/_authed': { loaderData: { unreadCount: 0 } }, '/_authed/posts/$postId': { loaderData: { post: createPost() } }, }, @@ -132,9 +139,10 @@ describe('a test router over the route tree of the application', () => { expect(first.state.matches.at(-1)?.status).toBe('success') const fetchMock = stubApi({ '/api/session': { user: null } }) - const second = routerTesting.createTestRouter({ - location: { to: '/posts/$postId', params: { postId: 'post-1' } }, + const second = createTestRouter({ + routeTree, context: { locale: 'en' }, + location: { to: '/posts/$postId', params: { postId: 'post-1' } }, }) await second.load() 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 index fa7709113a..7b3e16a321 100644 --- a/e2e/react-router/route-testing/tests/route-testing.test-d.tsx +++ b/e2e/react-router/route-testing/tests/route-testing.test-d.tsx @@ -1,24 +1,29 @@ +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 { - appTesting, - createPost, - routerTesting, - testUser, -} from '../src/test-utils' +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: { locale: 'en', session: { user: testUser }, user: testUser }, - loaderData: { post: createPost() }, - routes: { '/_authed': { loaderData: { unreadCount: 0 } } }, + context: signedInContext, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, } as const -describe('renderInRoute is typed from the generated route tree', () => { +describe('createIsolatedTestRouter is typed from the generated route tree', () => { test('accepts the complete state of a route', () => { - void routerTesting.renderInRoute(, postState) + void createIsolatedTestRouter(postState) }) test('rejects a missing context value', () => { @@ -27,53 +32,62 @@ describe('renderInRoute is typed from the generated route tree', () => { context: { locale: 'en', session: { user: testUser } }, } as const // @ts-expect-error `user` comes from the beforeLoad of `/_authed` and is missing - void routerTesting.renderInRoute(, withoutUser) + void createIsolatedTestRouter(withoutUser) }) test('rejects missing loader data of the route and of its ancestors', () => { - const { loaderData: _loaderData, ...withoutLoaderData } = postState + const withoutRouteData = { + ...postState, + loaderData: { '/_authed': { unreadCount: 0 } }, + } as const // @ts-expect-error the loader data of the route is missing - void routerTesting.renderInRoute(, withoutLoaderData) + void createIsolatedTestRouter(withoutRouteData) - const { routes: _routes, ...withoutAncestors } = postState + const withoutAncestorData = { + ...postState, + loaderData: { '/_authed/posts/$postId': { post: createPost() } }, + } as const // @ts-expect-error the loader data of `/_authed` is missing - void routerTesting.renderInRoute(, withoutAncestors) + void createIsolatedTestRouter(withoutAncestorData) }) test('rejects loader data of the wrong shape', () => { const wrongPost = { ...postState, - loaderData: { post: { id: 'post-1', title: 'No status' } }, + 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 routerTesting.renderInRoute(, wrongPost) + 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 routerTesting.renderInRoute(, unknownRoute) + void createIsolatedTestRouter(unknownRoute) }) - test('makes optional what the defaults of the application provide', () => { - const onlyOwnState = { - route: '/_authed/posts/$postId', - params: { postId: 'post-1' }, - loaderData: { post: createPost() }, - } as const - void appTesting.renderInRoute(, onlyOwnState) - - // @ts-expect-error without defaults the context and the ancestors are required - void routerTesting.renderInRoute(, onlyOwnState) + 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', () => { - routerTesting.createTestRouter({ + createTestRouter({ + routeTree, context: { locale: 'en' }, - routes: { - __root__: { + overrides: { + [rootRouteId]: { beforeLoad: ({ context }) => { expectTypeOf(context).toEqualTypeOf<{ locale: string }>() return { session: { user: testUser } } @@ -98,23 +112,25 @@ describe('createTestRouter is typed from the generated route tree', () => { test('rejects a replacement that returns the wrong data', () => { const wrongLoader = { + routeTree, context: { locale: 'en' }, - routes: { + overrides: { '/_authed/posts/$postId': { loader: (): { post: Pick } => ({ post: { id: '1' } }), }, }, } // @ts-expect-error the loader has to return a whole post - routerTesting.createTestRouter(wrongLoader) + 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 - routerTesting.createTestRouter(withoutParams) + createTestRouter(withoutParams) }) }) diff --git a/e2e/react-router/route-testing/tests/user-menu.test.tsx b/e2e/react-router/route-testing/tests/user-menu.test.tsx index d90ad195a2..dd4e552810 100644 --- a/e2e/react-router/route-testing/tests/user-menu.test.tsx +++ b/e2e/react-router/route-testing/tests/user-menu.test.tsx @@ -1,17 +1,25 @@ -import { fireEvent, screen, waitFor } from '@testing-library/react' +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 { appTesting, createPost, testUser } from '../src/test-utils' +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 () => { - await appTesting.renderInRoute(, { + const router = await createIsolatedTestRouter({ + routeTree, route: '/_authed/posts/$postId', + element: , params: { postId: 'post-1' }, - context: { user: { id: 'user-9', name: 'Grace' } }, - loaderData: { post: createPost() }, - routes: { '/_authed': { loaderData: { unreadCount: 7 } } }, + 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') @@ -19,11 +27,18 @@ describe('a component bound to a layout route', () => { }) test('navigating away changes the location and renders no other route', async () => { - const { router } = await appTesting.renderInRoute(, { + const router = await createIsolatedTestRouter({ + routeTree, route: '/_authed/posts/$postId', + element: , params: { postId: 'post-1' }, - loaderData: { post: createPost() }, + context: signedInContext, + loaderData: { + '/_authed': { unreadCount: 0 }, + '/_authed/posts/$postId': { post: createPost() }, + }, }) + render() fireEvent.click(screen.getByRole('link', { name: 'Sign out' })) @@ -35,9 +50,12 @@ describe('a component bound to a layout route', () => { test('cannot be rendered in a layout route that its own path does not lead to', async () => { await expect( - appTesting.renderInRoute(, { + createIsolatedTestRouter({ + routeTree, route: '/_authed', - context: { user: testUser }, + element: , + context: signedInContext, + loaderData: { '/_authed': { unreadCount: 0 } }, }), ).rejects.toThrow('The route "/_authed" is not matched at "/"') }) diff --git a/packages/react-router/src/testing.ts b/packages/react-router/src/testing.ts new file mode 100644 index 0000000000..c24b66061d --- /dev/null +++ b/packages/react-router/src/testing.ts @@ -0,0 +1,260 @@ +import { createMemoryHistory } from '@tanstack/history' +import { + assertIsolatedRouteLoaded, + assertRouteTestParams, + createIsolatedRouteTree, + createTestRouteTree, + setTestRouterLocation, +} from '@tanstack/router-core/testing' +import { createRouter } from './router' +import type * as React from 'react' +import type { RouterHistory } from '@tanstack/history' +import type { + AnyRoute, + RouterConstructorOptions, + RouterOptions, + TrailingSlashOption, + ValidateNavigateOptions, +} from '@tanstack/router-core' +import type { + AnyRouteTestOverrides, + RouteTestOverrides as CoreRouteTestOverrides, + IsolatedRouteState, +} 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 two. */ +export type CreateTestRouterOptions< + TRouteTree extends AnyRoute, + TLocation = unknown, + TTrailingSlashOption extends TrailingSlashOption = 'never', + TDefaultStructuralSharingOption extends boolean = false, + TRouterHistory extends RouterHistory = RouterHistory, + TDehydrated extends Record = Record, +> = 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`. Defaults to `/`. + */ + location?: ValidateNavigateOptions< + Router< + TRouteTree, + TTrailingSlashOption, + TDefaultStructuralSharingOption, + TRouterHistory, + TDehydrated + >, + TLocation + > + /** + * Per-route overrides. A route that is not listed keeps the application's + * options. + */ + overrides?: RouteTestOverrides +} + +/** The options of `createIsolatedTestRouter`. */ +export type CreateIsolatedTestRouterOptions< + TRouteTree extends AnyRoute, + TId, + 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: React.ReactElement +} & IsolatedRouteState + +interface AnyCreateTestRouterOptions { + routeTree: AnyRoute + location?: object + overrides?: AnyRouteTestOverrides + history?: RouterHistory +} + +interface AnyCreateIsolatedTestRouterOptions { + routeTree: AnyRoute + element: React.ReactElement + route: string + params?: Record + search?: Record + context?: Record + loaderData?: Record +} + +/** + * 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 +> { + const { routeTree, location, overrides, history, ...routerOptions } = + options as AnyCreateTestRouterOptions + const router = createRouter({ + ...routerOptions, + routeTree: createTestRouteTree(routeTree, overrides), + history: history ?? createMemoryHistory(), + } as any) + + if (location) { + setTestRouterLocation(router, location) + } + + return router 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 async function createIsolatedTestRouter< + TRouteTree extends AnyRoute, + // `IsolatedRouteState` 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 { + routeTree, + element, + route, + params, + search, + context, + loaderData, + ...routerOptions + } = options as unknown as AnyCreateIsolatedTestRouterOptions + + const router = createRouter({ + ...routerOptions, + // Nothing of the application renders around the element, and an error + // it throws reaches the test instead of an error component. + defaultComponent: undefined, + defaultErrorComponent: undefined, + defaultPendingComponent: undefined, + disableGlobalCatchBoundary: true, + routeTree: createIsolatedRouteTree(routeTree, { + routeId: route, + component: () => element, + loaderData: new Map(Object.entries(loaderData ?? {})), + }), + history: createMemoryHistory(), + context, + } as any) + + assertRouteTestParams(router, route, params) + setTestRouterLocation(router, { + to: router.routesById[route]!.fullPath, + params, + search, + }) + await router.load() + assertIsolatedRouteLoaded(router, route) + + return router as any +} diff --git a/packages/react-router/src/testing.tsx b/packages/react-router/src/testing.tsx deleted file mode 100644 index 80e3f0122c..0000000000 --- a/packages/react-router/src/testing.tsx +++ /dev/null @@ -1,359 +0,0 @@ -import { createMemoryHistory } from '@tanstack/history' -import { - assertIsolatedRouteLoaded, - assertRouteTestParams, - createIsolatedRouteTree, - createTestRouteTree, - setTestRouterLocation, -} from '@tanstack/router-core/testing' -import { RouterProvider } from './RouterProvider' -import { createRouter } from './router' -import type * as React from 'react' -import type { RouterHistory } from '@tanstack/history' -import type { - AnyRoute, - RouteIds, - RouterOptions, - TrailingSlashOption, - ValidateNavigateOptions, -} from '@tanstack/router-core' -import type { - AnyRouteTestOverrides, - RouteTestOverrides as CoreRouteTestOverrides, - RouterTestingDefaults as CoreRouterTestingDefaults, - RouteTestOptions, - TestRouterContextOption, -} from '@tanstack/router-core/testing' -import type { - ErrorRouteComponent, - NotFoundRouteComponent, - RouteComponent, -} from './route' -import type { Router } from './router' - -export type { - RouteTestBeforeLoadFn, - RouteTestContextFn, - RouteTestLoaderFn, - RouteTestOptions, -} 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. */ -export type RouteTestOverrides = - CoreRouteTestOverrides - -/** Defaults an application sets once for all of its route tests. */ -export type RouterTestingDefaults = - CoreRouterTestingDefaults - -/** - * Renders the element a test hands over, for example `render` from - * `@testing-library/react` or from `vitest-browser-react`. - */ -export type RouterTestingRenderFn = (ui: React.ReactElement) => unknown - -/** Router options shared by every test router. */ -export type TestRouterBaseOptions< - TRouteTree extends AnyRoute, - TTrailingSlashOption extends TrailingSlashOption, - TDefaultStructuralSharingOption extends boolean, -> = Omit< - RouterOptions< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption, - RouterHistory, - Record - >, - 'routeTree' | 'history' | 'context' -> - -export interface RouterTestingConfig< - TRouteTree extends AnyRoute, - TTrailingSlashOption extends TrailingSlashOption, - TDefaultStructuralSharingOption extends boolean, - TDefaults, - TRender, -> { - /** The application's route tree. Every test router is built from a copy. */ - routeTree: TRouteTree - /** - * Router options for every test router, such as `Wrap` for providers. The - * tree, the history and the context are set per test. - */ - routerOptions?: TestRouterBaseOptions< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption - > - /** - * Context values and overrides every test starts with. What is given here - * becomes optional in each test. - */ - // The intersection lets functions inside the defaults take their parameter - // types from the route tree while `TDefaults` records what was given. - defaults?: TDefaults & RouterTestingDefaults - /** - * The render function of the test library. Needed for `renderInRoute`. - */ - render?: TRender -} - -export type CreateTestRouterOptions< - TRouteTree extends AnyRoute, - TTrailingSlashOption extends TrailingSlashOption, - TDefaultStructuralSharingOption extends boolean, - TDefaults, - TLocation, -> = { - /** - * Where the router starts, typed like the options of `navigate`. Defaults - * to `/`. - */ - location?: ValidateNavigateOptions< - Router, - TLocation - > - /** - * A history to start from instead of `location`, for entries that are not - * valid navigation targets. - */ - history?: RouterHistory - /** - * Per-route overrides. A route that is not listed keeps the application's - * options. - */ - routes?: RouteTestOverrides -} & TestRouterContextOption - -export type RenderInRouteOptions< - TRouteTree extends AnyRoute, - TId, - TDefaults, -> = RouteTestOptions - -export interface RenderInRouteResult< - TRouteTree extends AnyRoute, - TTrailingSlashOption extends TrailingSlashOption, - TDefaultStructuralSharingOption extends boolean, - TRender, -> { - router: Router< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption - > - /** What the configured `render` function returned. */ - result: TRender extends (...args: Array) => infer TResult - ? Awaited - : never -} - -export interface RouterTesting< - TRouteTree extends AnyRoute, - TTrailingSlashOption extends TrailingSlashOption, - TDefaultStructuralSharingOption extends boolean, - TDefaults, - TRender, -> { - /** - * Creates a router over a copy of the route tree. Every route runs the - * application's own lifecycle unless `routes` replaces part of it. - * - * The router has not loaded yet. Render it with `RouterProvider`, or call - * `router.load()` first when the test needs the first render to be complete. - */ - createTestRouter: ( - ...args: {} extends CreateTestRouterOptions< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption, - TDefaults, - TLocation - > - ? [ - options?: CreateTestRouterOptions< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption, - TDefaults, - TLocation - >, - ] - : [ - options: CreateTestRouterOptions< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption, - TDefaults, - TLocation - >, - ] - ) => Router - /** - * Renders one element inside one route, with the route's state supplied by - * the test. - * - * 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. - */ - renderInRoute: >( - element: React.ReactElement, - options: RenderInRouteOptions, - ) => Promise< - RenderInRouteResult< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption, - TRender - > - > -} - -interface AnyRenderInRouteOptions { - route: string - params?: Record - search?: Record - context?: Record - loaderData?: unknown - routes?: Record -} - -interface AnyCreateTestRouterOptions { - location?: object - history?: RouterHistory - routes?: AnyRouteTestOverrides - context?: Record -} - -interface AnyRouterTestingDefaults { - context?: Record - routes?: AnyRouteTestOverrides -} - -/** - * Creates the test helpers for one application. Call it once, for example in - * a `test-utils` file, with the application's route tree. - * - * ```tsx - * import { render } from '@testing-library/react' - * import { createRouterTesting } from '@tanstack/react-router/testing' - * import { routeTree } from './routeTree.gen' - * - * export const { createTestRouter, renderInRoute } = createRouterTesting({ - * routeTree, - * render, - * }) - * ``` - */ -export function createRouterTesting< - TRouteTree extends AnyRoute, - TTrailingSlashOption extends TrailingSlashOption = 'never', - TDefaultStructuralSharingOption extends boolean = false, - const TDefaults = {}, - TRender extends RouterTestingRenderFn | undefined = undefined, ->( - config: RouterTestingConfig< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption, - TDefaults, - TRender - >, -): RouterTesting< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption, - TDefaults, - TRender -> { - const defaults = config.defaults as AnyRouterTestingDefaults | undefined - - const createTestRouter = (options: AnyCreateTestRouterOptions = {}) => { - const router = createRouter({ - ...config.routerOptions, - routeTree: createTestRouteTree( - config.routeTree, - defaults?.routes, - options.routes, - ), - history: options.history ?? createMemoryHistory(), - context: { ...defaults?.context, ...options.context }, - } as any) - - if (options.location && !options.history) { - setTestRouterLocation(router, options.location) - } - - return router - } - - const renderInRoute = async ( - element: React.ReactElement, - options: AnyRenderInRouteOptions, - ) => { - const render = config.render - if (!render) { - throw new Error( - 'renderInRoute needs a render function. Pass `render` to createRouterTesting, for example the one from @testing-library/react.', - ) - } - - const loaderData = new Map() - const seedLoaderData = ( - routes: Record | undefined, - ) => { - for (const routeId in routes) { - const seed = routes[routeId] - if (seed && 'loaderData' in seed) { - loaderData.set(routeId, seed.loaderData) - } - } - } - seedLoaderData(defaults?.routes) - seedLoaderData(options.routes) - if ('loaderData' in options) { - loaderData.set(options.route, options.loaderData) - } - - const router = createRouter({ - ...config.routerOptions, - // Nothing of the application renders around the element, and an error - // it throws reaches the test instead of an error component. - defaultComponent: undefined, - defaultErrorComponent: undefined, - defaultPendingComponent: undefined, - disableGlobalCatchBoundary: true, - routeTree: createIsolatedRouteTree(config.routeTree, { - routeId: options.route, - component: () => element, - loaderData, - }), - history: createMemoryHistory(), - context: { ...defaults?.context, ...options.context }, - } as any) - - assertRouteTestParams(router, options.route, options.params) - setTestRouterLocation(router, { - to: router.routesById[options.route]!.fullPath, - params: options.params, - search: options.search, - }) - await router.load() - assertIsolatedRouteLoaded(router, options.route) - - const result = await render() - return { router, result } - } - - return { createTestRouter, renderInRoute } as any -} diff --git a/packages/react-router/tests/testing.test-d.tsx b/packages/react-router/tests/testing.test-d.tsx index b3ce80319f..0a336a7878 100644 --- a/packages/react-router/tests/testing.test-d.tsx +++ b/packages/react-router/tests/testing.test-d.tsx @@ -1,11 +1,8 @@ -import { render } from '@testing-library/react' import { describe, expectTypeOf, test } from 'vitest' -import { createRootRouteWithContext, createRoute } from '../src' -import { createRouterTesting } from '../src/testing' -import type * as React from 'react' -import type { RenderResult } from '@testing-library/react' +import { createRootRouteWithContext, createRoute, rootRouteId } from '../src' +import { createIsolatedTestRouter, createTestRouter } from '../src/testing' import type { Router, SearchSchemaInput } from '../src' -import type { RenderInRouteOptions } from '../src/testing' +import type { IsolatedRouteState, RouteTestOverrides } from '../src/testing' interface User { id: string @@ -60,205 +57,147 @@ type RequiredKeys = { [K in keyof T]-?: {} extends Pick ? never : K }[keyof T] -const testing = createRouterTesting({ routeTree, render }) - -const testingWithDefaults = createRouterTesting({ - routeTree, - render, - defaults: { - context: { locale: 'en', user: { id: 'default' } }, - routes: { '/_authed': { loaderData: { unreadCount: 0 } } }, - }, -}) - const postState = { + routeTree, route: '/_authed/posts/$postId', + element:
, params: { postId: '1' }, context: { locale: 'en', session: { user: null }, user: { id: '1' } }, - loaderData: { post: { id: '1' } }, - routes: { '/_authed': { loaderData: { unreadCount: 1 } } }, + loaderData: { + '/_authed': { unreadCount: 1 }, + '/_authed/posts/$postId': { post: { id: '1' } }, + }, } as const -describe('renderInRoute', () => { +describe('createIsolatedTestRouter', () => { test('asks for everything the route promises to its components', () => { - type PostOptions = RenderInRouteOptions< - RouteTree, - '/_authed/posts/$postId', - {} - > + type PostState = IsolatedRouteState - expectTypeOf>().toEqualTypeOf< - 'route' | 'params' | 'context' | 'loaderData' | 'routes' + expectTypeOf>().toEqualTypeOf< + 'route' | 'params' | 'context' | 'loaderData' >() - expectTypeOf< - PostOptions['route'] - >().toEqualTypeOf<'/_authed/posts/$postId'>() - expectTypeOf().toEqualTypeOf<'postId'>() - expectTypeOf().toEqualTypeOf() - expectTypeOf().toEqualTypeOf< + expectTypeOf<'/_authed/posts/$postId'>().toExtend() + expectTypeOf().toEqualTypeOf<'postId'>() + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf< 'locale' | 'session' | 'user' >() - expectTypeOf().toEqualTypeOf() - expectTypeOf().toEqualTypeOf() - expectTypeOf().toEqualTypeOf() - expectTypeOf().toEqualTypeOf<{ - post: { id: string } + expectTypeOf().toEqualTypeOf() + expectTypeOf().toEqualTypeOf() + expectTypeOf>().toEqualTypeOf< + '/_authed' | '/_authed/posts/$postId' + >() + expectTypeOf().toEqualTypeOf<{ + unreadCount: number }>() - expectTypeOf().toEqualTypeOf<{ - loaderData: { unreadCount: number } - }>() - expectTypeOf>().toEqualTypeOf<{ + expectTypeOf< + PostState['loaderData']['/_authed/posts/$postId'] + >().toEqualTypeOf<{ post: { id: string } }>() + expectTypeOf>().toEqualTypeOf<{ tab?: string }>() }) test('asks for nothing a route does not have', () => { - type SettingsOptions = RenderInRouteOptions< - RouteTree, - '/_authed/settings', - {} - > + type SettingsState = IsolatedRouteState // No path params and no loader of its own, but an ancestor with a loader. - expectTypeOf>().toEqualTypeOf< - 'route' | 'context' | 'routes' + expectTypeOf>().toEqualTypeOf< + 'route' | 'context' | 'loaderData' >() + expectTypeOf< + RequiredKeys + >().toEqualTypeOf<'/_authed'>() - type LoginOptions = RenderInRouteOptions + type LoginState = IsolatedRouteState // Its beforeLoad adds nothing, so the context is the one of the root route. - expectTypeOf>().toEqualTypeOf< + expectTypeOf>().toEqualTypeOf< 'route' | 'context' >() - expectTypeOf().toEqualTypeOf< + expectTypeOf().toEqualTypeOf< 'locale' | 'session' >() }) - test('accepts the complete state and returns the router and the render result', async () => { - const rendered = await testing.renderInRoute(
, postState) - - expectTypeOf(rendered.router).toEqualTypeOf< - Router + test('accepts the complete state and resolves to the router type', () => { + expectTypeOf(createIsolatedTestRouter(postState)).toEqualTypeOf< + Promise> >() - expectTypeOf(rendered.result).toEqualTypeOf() }) 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 testing.renderInRoute(
, withoutContext) + void createIsolatedTestRouter(withoutContext) const withoutUser = { ...postState, context: { locale: 'en', session: { user: null } }, } as const // @ts-expect-error `user` is missing from the context - void testing.renderInRoute(
, withoutUser) + void createIsolatedTestRouter(withoutUser) - const { loaderData: _loaderData, ...withoutLoaderData } = postState + const withoutRouteLoaderData = { + ...postState, + loaderData: { '/_authed': { unreadCount: 1 } }, + } as const // @ts-expect-error the loader data of the route is missing - void testing.renderInRoute(
, withoutLoaderData) + void createIsolatedTestRouter(withoutRouteLoaderData) - const { routes: _routes, ...withoutAncestors } = postState + const withoutAncestorLoaderData = { + ...postState, + loaderData: { '/_authed/posts/$postId': { post: { id: '1' } } }, + } as const // @ts-expect-error the loader data of `/_authed` is missing - void testing.renderInRoute(
, withoutAncestors) + void createIsolatedTestRouter(withoutAncestorLoaderData) const { params: _params, ...withoutParams } = postState // @ts-expect-error the path params are missing - void testing.renderInRoute(
, withoutParams) + void createIsolatedTestRouter(withoutParams) - const wrongLoaderData = { ...postState, loaderData: { post: 1 } } as const + const wrongLoaderData = { + ...postState, + loaderData: { + '/_authed': { unreadCount: 1 }, + '/_authed/posts/$postId': { post: 1 }, + }, + } as const // @ts-expect-error `post` is not a number - void testing.renderInRoute(
, wrongLoaderData) + void createIsolatedTestRouter(wrongLoaderData) const unknownRoute = { ...postState, route: '/unknown' } as const // @ts-expect-error not a route id of the tree - void testing.renderInRoute(
, unknownRoute) + void createIsolatedTestRouter(unknownRoute) }) - test('makes optional what the defaults of the application provide', () => { - const { routes: _routes, ...withoutAncestors } = postState - const withDefaults = { - ...withoutAncestors, - context: { session: { user: null } }, - } as const - void testingWithDefaults.renderInRoute(
, withDefaults) + test('takes the root route by rootRouteId', () => { + type RootState = IsolatedRouteState + expectTypeOf>().toEqualTypeOf<'route' | 'context'>() - const withoutSession = { ...withoutAncestors, context: {} } as const - // @ts-expect-error `session` is not among the defaults - void testingWithDefaults.renderInRoute(
, withoutSession) - - type PostOptions = RenderInRouteOptions< - RouteTree, - '/_authed/posts/$postId', - { - context: { locale: string; user: User } - routes: { '/_authed': { loaderData: { unreadCount: number } } } - } - > - expectTypeOf>().toEqualTypeOf< - 'route' | 'params' | 'context' | 'loaderData' - >() - expectTypeOf< - RequiredKeys - >().toEqualTypeOf<'session'>() - }) -}) - -describe('createRouterTesting', () => { - test('types the defaults from the route tree', () => { - createRouterTesting({ + void createIsolatedTestRouter({ routeTree, - defaults: { - context: { locale: 'en', session: { user: null } }, - routes: { - '/_authed': { - beforeLoad: ({ context }) => { - expectTypeOf(context.session).toEqualTypeOf() - return { user: { id: '1' } } - }, - }, - }, - }, + route: rootRouteId, + element:
, + context: { locale: 'en', session: { user: null } }, }) - - createRouterTesting({ - routeTree, - // @ts-expect-error `locale` is a string - defaults: { context: { locale: 1 } }, - }) - }) - - test('takes the type of the render result from the render function', async () => { - const withAsyncRender = createRouterTesting({ - routeTree, - render: (ui: React.ReactElement) => Promise.resolve({ ui }), - }) - const rendered = await withAsyncRender.renderInRoute(
, postState) - - expectTypeOf(rendered.result).toEqualTypeOf<{ ui: React.ReactElement }>() }) }) describe('createTestRouter', () => { test('returns the router type of the route tree', () => { expectTypeOf( - testing.createTestRouter({ context: { locale: 'en' } }), + createTestRouter({ routeTree, context: { locale: 'en' } }), ).toEqualTypeOf>() }) - test('requires the router context unless the defaults provide it', () => { + test('requires the router context like createRouter', () => { + const withoutContext = { routeTree } as const // @ts-expect-error the router context is required - testing.createTestRouter() - - const withoutContext = {} as const - // @ts-expect-error the router context is required - testing.createTestRouter(withoutContext) - - testingWithDefaults.createTestRouter() + createTestRouter(withoutContext) }) test('types the location like navigation options', () => { - testing.createTestRouter({ + createTestRouter({ + routeTree, context: { locale: 'en' }, location: { to: '/posts/$postId', @@ -268,25 +207,33 @@ describe('createTestRouter', () => { }) const withoutParams = { + routeTree, context: { locale: 'en' }, location: { to: '/posts/$postId' }, } as const // @ts-expect-error the path params of the location are missing - testing.createTestRouter(withoutParams) + createTestRouter(withoutParams) const unknownPath = { + routeTree, context: { locale: 'en' }, location: { to: '/unknown' }, } as const // @ts-expect-error not a path of the tree - testing.createTestRouter(unknownPath) + createTestRouter(unknownPath) }) test('types replacements and seeds from the route', () => { - testing.createTestRouter({ + createTestRouter({ + routeTree, context: { locale: 'en' }, - routes: { - __root__: { context: { session: { user: null } } }, + overrides: { + [rootRouteId]: { + beforeLoad: ({ context }) => { + expectTypeOf(context.locale).toEqualTypeOf() + return { session: { user: null } } + }, + }, '/_authed': { beforeLoad: ({ context }) => { expectTypeOf(context.locale).toEqualTypeOf() @@ -309,44 +256,77 @@ describe('createTestRouter', () => { }, }, }) + + 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' }, - routes: { '/_authed': { loaderData: { unreadCount: 'many' } } }, + overrides: { '/_authed': { loaderData: { unreadCount: 'many' } } }, } as const // @ts-expect-error `unreadCount` is a number - testing.createTestRouter(wrongSeed) + createTestRouter(wrongSeed) const wrongContextSeed = { + routeTree, context: { locale: 'en' }, - routes: { '/_authed': { context: { user: 'nobody' } } }, + overrides: { '/_authed': { routeContext: { user: 'nobody' } } }, } as const // @ts-expect-error `user` is an object - testing.createTestRouter(wrongContextSeed) + 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' }, - routes: { + overrides: { '/_authed/posts/$postId': { loader: () => ({ post: 'none' }) }, }, } // @ts-expect-error the loader has to return the loader data of the route - testing.createTestRouter(wrongLoader) + createTestRouter(wrongLoader) const wrongBeforeLoad = { + routeTree, context: { locale: 'en' }, - routes: { '/_authed': { beforeLoad: () => ({ user: 'nobody' }) } }, + overrides: { '/_authed': { beforeLoad: () => ({ user: 'nobody' }) } }, } // @ts-expect-error beforeLoad has to return what the route's own returns - testing.createTestRouter(wrongBeforeLoad) + createTestRouter(wrongBeforeLoad) const unknownRoute = { + routeTree, context: { locale: 'en' }, - routes: { '/unknown': {} }, + overrides: { '/unknown': {} }, } as const // @ts-expect-error not a route id of the tree - testing.createTestRouter(unknownRoute) + createTestRouter(unknownRoute) }) }) diff --git a/packages/react-router/tests/testing.test.tsx b/packages/react-router/tests/testing.test.tsx index 44c943f32c..75c8c8562c 100644 --- a/packages/react-router/tests/testing.test.tsx +++ b/packages/react-router/tests/testing.test.tsx @@ -15,8 +15,9 @@ import { createRootRouteWithContext, createRoute, redirect, + rootRouteId, } from '../src' -import { createRouterTesting } from '../src/testing' +import { createIsolatedTestRouter, createTestRouter } from '../src/testing' import type { SearchSchemaInput } from '../src' afterEach(() => { @@ -167,14 +168,19 @@ function createApp() { } } +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 { createTestRouter } = createRouterTesting({ - routeTree: app.routeTree, - }) const router = createTestRouter({ + routeTree: app.routeTree, location: { to: '/posts/$postId', params: { postId: '1' } }, context: { locale: 'en' }, }) @@ -198,19 +204,17 @@ describe('createTestRouter', () => { test('replaces the options a test names and keeps the rest', async () => { const app = createApp() - const { createTestRouter } = createRouterTesting({ - routeTree: app.routeTree, - }) const router = createTestRouter({ + routeTree: app.routeTree, location: { to: '/posts/$postId', params: { postId: '2' }, search: { tab: 'comments' }, }, context: { locale: 'de' }, - routes: { - __root__: { context: { session: { user: testUser } } }, + overrides: { + [rootRouteId]: { routeContext: { session: { user: testUser } } }, '/_authed': { loaderData: { unreadCount: 7 } }, '/_authed/posts/$postId': { loader: ({ params }) => ({ @@ -234,14 +238,12 @@ describe('createTestRouter', () => { test('replaces beforeLoad, the context option and components', async () => { const app = createApp() - const { createTestRouter } = createRouterTesting({ - routeTree: app.routeTree, - }) const router = createTestRouter({ + routeTree: app.routeTree, location: { to: '/posts/$postId', params: { postId: '1' } }, context: { locale: 'en' }, - routes: { + overrides: { '/_authed': { beforeLoad: ({ context }) => ({ user: { id: 'derived', name: `Derived in ${context.locale}` }, @@ -273,14 +275,12 @@ describe('createTestRouter', () => { test('removes an option that is overridden with undefined', async () => { const app = createApp() - const { createTestRouter } = createRouterTesting({ - routeTree: app.routeTree, - }) const router = createTestRouter({ + routeTree: app.routeTree, location: { to: '/posts/$postId', params: { postId: '1' } }, context: { locale: 'en' }, - routes: { '/_authed': { loader: undefined } }, + overrides: { '/_authed': { loader: undefined } }, }) await router.load() @@ -294,14 +294,12 @@ describe('createTestRouter', () => { 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 { createTestRouter } = createRouterTesting({ - routeTree: app.routeTree, - }) const first = createTestRouter({ + routeTree: app.routeTree, location: { to: '/posts/$postId', params: { postId: '1' } }, context: { locale: 'en' }, - routes: { + overrides: { '/_authed/posts/$postId': { loaderData: { post: { id: '1', title: 'Seeded post' } }, }, @@ -314,6 +312,7 @@ describe('createTestRouter', () => { expect(app.postRoute.options.loader).toBe(originalLoader) const second = createTestRouter({ + routeTree: app.routeTree, location: { to: '/posts/$postId', params: { postId: '1' } }, context: { locale: 'en' }, }) @@ -327,9 +326,7 @@ describe('createTestRouter', () => { const app = createApp() expect(app.postRoute.id).toBeUndefined() - createRouterTesting({ routeTree: app.routeTree }).createTestRouter({ - context: { locale: 'en' }, - }) + createTestRouter({ routeTree: app.routeTree, context: { locale: 'en' } }) expect(app.postRoute.id).toBe('/_authed/posts/$postId') expect(app.postRoute.fullPath).toBe('/posts/$postId') @@ -337,13 +334,18 @@ describe('createTestRouter', () => { expect(app.authedRoute.id).toBe('/_authed') }) - test('starts from a history instead of a location', async () => { + test('uses a memory history, or the history it is given', async () => { const app = createApp() - const { createTestRouter } = createRouterTesting({ + + 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' }, }) @@ -352,13 +354,29 @@ describe('createTestRouter', () => { 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 { createTestRouter } = createRouterTesting({ - routeTree: app.routeTree, - }) const real = createTestRouter({ + routeTree: app.routeTree, location: { to: '/lazy' }, context: { locale: 'en' }, }) @@ -367,77 +385,37 @@ describe('createTestRouter', () => { unmount() const overridden = createTestRouter({ + routeTree: app.routeTree, location: { to: '/lazy' }, context: { locale: 'en' }, - routes: { '/lazy': { component: () =>

Test component

} }, + overrides: { '/lazy': { component: () =>

Test component

} }, }) render() expect(await screen.findByText('Test component')).toBeInTheDocument() expect(screen.queryByText('Lazy component')).not.toBeInTheDocument() }) - test('applies the defaults of the application, and a test wins over them', async () => { - const app = createApp() - const { createTestRouter } = createRouterTesting({ - routeTree: app.routeTree, - defaults: { - context: { locale: 'fr' }, - routes: { - __root__: { context: { session: { user: testUser } } }, - '/_authed': { loaderData: { unreadCount: 3 } }, - }, - }, - }) - - const withDefaults = createTestRouter({ - location: { to: '/posts/$postId', params: { postId: '1' } }, - }) - const { unmount } = render() - expect( - await screen.findByText( - 'Test user reads post 1 in fr on tab details with 3 unread in real scope', - ), - ).toBeInTheDocument() - unmount() - - const withOwnValues = createTestRouter({ - location: { to: '/posts/$postId', params: { postId: '1' } }, - context: { locale: 'it' }, - routes: { '/_authed': { loaderData: { unreadCount: 9 } } }, - }) - render() - expect( - await screen.findByText( - 'Test user reads post 1 in it on tab details with 9 unread in real scope', - ), - ).toBeInTheDocument() - }) - test('rejects an override for a route that does not exist', () => { const app = createApp() - const { createTestRouter } = createRouterTesting({ - routeTree: app.routeTree, - }) expect(() => createTestRouter({ + routeTree: app.routeTree, context: { locale: 'en' }, // @ts-expect-error not a route id of this tree - routes: { '/missing': { component: () => null } }, + overrides: { '/missing': { component: () => null } }, }), ).toThrow('The route "/missing" does not exist in the route tree') }) - test('rejects an override with both a loader and loader data', () => { + test('rejects conflicting overrides', () => { const app = createApp() - const { createTestRouter } = createRouterTesting({ - routeTree: app.routeTree, - }) expect(() => createTestRouter({ + routeTree: app.routeTree, context: { locale: 'en' }, - routes: { + overrides: { '/_authed': { loader: () => ({ unreadCount: 1 }), loaderData: { unreadCount: 2 }, @@ -445,32 +423,41 @@ describe('createTestRouter', () => { }, }), ).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('renderInRoute', () => { +describe('createIsolatedTestRouter', () => { test('renders one element in one route with the state the test supplies', async () => { const app = createApp() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - render, - }) - const { router } = await renderInRoute(, { + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, route: '/_authed/posts/$postId', + element: , params: { postId: '5' }, search: { tab: 'comments' }, - context: { - locale: 'en', - session: { user: testUser }, - user: testUser, - scope: 'seeded scope', + context: seededContext, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } }, }, - loaderData: { post: { id: '5', title: 'Seeded post' } }, - routes: { '/_authed': { loaderData: { unreadCount: 4 } } }, }) + render() - // The first render is complete: nothing is pending. + // The router has loaded, so the first render is complete. expect(screen.getByRole('heading')).toHaveTextContent('Seeded post') expect( screen.getByText( @@ -488,85 +475,48 @@ describe('renderInRoute', () => { test('sends search params through validateSearch', async () => { const app = createApp() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - render, - }) const state = { + routeTree: app.routeTree, route: '/_authed/posts/$postId', params: { postId: '5' }, - context: { - locale: 'en', - session: { user: testUser }, - user: testUser, - scope: 'seeded scope', + context: seededContext, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } }, }, - loaderData: { post: { id: '5', title: 'Seeded post' } }, - routes: { '/_authed': { loaderData: { unreadCount: 4 } } }, } as const - await renderInRoute(, state) + const router = await createIsolatedTestRouter({ + ...state, + element: , + }) + render() expect(screen.getByText(/on tab details/)).toBeInTheDocument() - cleanup() await expect( - renderInRoute(, { + createIsolatedTestRouter({ ...state, + element: , search: { tab: 'broken' }, }), ).rejects.toThrow('Unknown tab') }) - test('takes context and loader data from the defaults of the application', async () => { - const app = createApp() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - render, - defaults: { - context: { - locale: 'en', - session: { user: testUser }, - user: testUser, - scope: 'default scope', - }, - routes: { '/_authed': { loaderData: { unreadCount: 2 } } }, - }, - }) - - await renderInRoute(, { - route: '/_authed/posts/$postId', - params: { postId: '5' }, - context: { user: realUser }, - loaderData: { post: { id: '5', title: 'Seeded post' } }, - }) - - expect( - screen.getByText( - 'Real user reads post 5 in en on tab details with 2 unread in default scope', - ), - ).toBeInTheDocument() - expect(app.calls).toEqual([]) - }) - test('navigates with the real router and renders no other route', async () => { const app = createApp() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - render, - }) - const { router } = await renderInRoute(, { + const router = await createIsolatedTestRouter({ + routeTree: app.routeTree, route: '/_authed/posts/$postId', + element: , params: { postId: '5' }, - context: { - locale: 'en', - session: { user: testUser }, - user: testUser, - scope: 'seeded scope', + context: seededContext, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } }, }, - loaderData: { post: { id: '5', title: 'Seeded post' } }, - routes: { '/_authed': { loaderData: { unreadCount: 4 } } }, }) + render() fireEvent.click(screen.getByRole('link', { name: 'Sign out' })) @@ -579,37 +529,33 @@ describe('renderInRoute', () => { test('does not load lazy routes', async () => { const app = createApp() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - render, - }) - await renderInRoute(

In the lazy route

, { + 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('applies the router options of the application, such as Wrap', async () => { + test('passes the other options to the router, except the default components', async () => { const app = createApp() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - render, - routerOptions: { - Wrap: ({ children }) => ( -
{children}
- ), - defaultComponent: () =>

Default component

, - }, - }) - await renderInRoute(

Element

, { + 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() @@ -617,45 +563,41 @@ describe('renderInRoute', () => { test('lets an error of the element reach the test', async () => { const app = createApp() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - render, - }) const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {}) function Broken(): never { throw new Error('The element is broken') } - await expect( - renderInRoute(, { - route: '/login', - context: { locale: 'en', session: { user: null } }, - }), - ).rejects.toThrow('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() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - render, - }) await expect( - renderInRoute(, { + createIsolatedTestRouter({ + routeTree: app.routeTree, route: '/_authed/posts/$postId', + element: , // @ts-expect-error `postId` is missing params: {}, - context: { - locale: 'en', - session: { user: testUser }, - user: testUser, - scope: 'seeded scope', + context: seededContext, + loaderData: { + '/_authed': { unreadCount: 4 }, + '/_authed/posts/$postId': { + post: { id: '5', title: 'Seeded post' }, + }, }, - loaderData: { post: { id: '5', title: 'Seeded post' } }, - routes: { '/_authed': { loaderData: { unreadCount: 4 } } }, }), ).rejects.toThrow( 'Missing path params for route "/_authed/posts/$postId": postId.', @@ -664,50 +606,28 @@ describe('renderInRoute', () => { test('fails when the path of the route does not lead to it', async () => { const app = createApp() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - render, - }) await expect( - renderInRoute(

Element

, { + createIsolatedTestRouter({ + routeTree: app.routeTree, route: '/_authed', - context: { - locale: 'en', - session: { user: testUser }, - user: testUser, - }, - loaderData: { unreadCount: 4 }, + 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() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - render, - }) await expect( - renderInRoute(

Element

, { + 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') }) - - test('needs a render function', async () => { - const app = createApp() - const { renderInRoute } = createRouterTesting({ - routeTree: app.routeTree, - }) - - await expect( - renderInRoute(

Element

, { - route: '/login', - context: { locale: 'en', session: { user: null } }, - }), - ).rejects.toThrow('renderInRoute needs a render function') - }) }) diff --git a/packages/react-router/vite.config.ts b/packages/react-router/vite.config.ts index 22e54b4032..7d82212668 100644 --- a/packages/react-router/vite.config.ts +++ b/packages/react-router/vite.config.ts @@ -32,7 +32,7 @@ export default mergeConfig( './src/index.dev.tsx', './src/ssr/client.ts', './src/ssr/server.ts', - './src/testing.tsx', + './src/testing.ts', ], srcDir: './src', }), diff --git a/packages/router-core/src/testing/index.ts b/packages/router-core/src/testing/index.ts index ff09029b05..2b4181e502 100644 --- a/packages/router-core/src/testing/index.ts +++ b/packages/router-core/src/testing/index.ts @@ -12,13 +12,11 @@ export type { IsolatedRouteTreeOptions, } from './routeTree' export type { + IsolatedRouteState, RouteTestBeforeLoadFn, RouteTestComponents, RouteTestContextFn, RouteTestLoaderFn, - RouteTestOptions, RouteTestOverride, RouteTestOverrides, - RouterTestingDefaults, - TestRouterContextOption, } from './types' diff --git a/packages/router-core/src/testing/routeTree.ts b/packages/router-core/src/testing/routeTree.ts index 46cc33c997..2e7388204e 100644 --- a/packages/router-core/src/testing/routeTree.ts +++ b/packages/router-core/src/testing/routeTree.ts @@ -11,8 +11,9 @@ type RouteOptionsPatch = Record export interface AnyRouteTestOverride { beforeLoad?: unknown loader?: unknown - loaderData?: unknown context?: unknown + loaderData?: unknown + routeContext?: unknown component?: unknown pendingComponent?: unknown errorComponent?: unknown @@ -24,7 +25,11 @@ export type AnyRouteTestOverrides = Record< AnyRouteTestOverride | undefined > -const componentOptions = [ +/** Override keys that replace the route option of the same name. */ +const replacedOptions = [ + 'beforeLoad', + 'loader', + 'context', 'component', 'pendingComponent', 'errorComponent', @@ -142,71 +147,69 @@ function assertKnownRouteIds(routeTree: AnyRoute, ids: Iterable) { } function applyOverride( - patch: RouteOptionsPatch, routeId: string, override: AnyRouteTestOverride, -) { - if ('loader' in override && 'loaderData' in override) { +): 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 "loader" and "loaderData". Pass one of them.`, + `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 ('loader' in override) { - patch.loader = override.loader - } - if ('context' in override) { - const context = override.context - if (typeof context === 'function') { - patch.context = context - } else { - // A seed stands for everything the route contributes to the context, - // so neither of the two options that produce it may run. - patch.context = () => context - patch.beforeLoad = undefined - } - } - if ('beforeLoad' in override) { - patch.beforeLoad = override.beforeLoad - } - for (const key of componentOptions) { - if (key in override) { - patch[key] = override[key] - } + 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. - * Later override maps win over earlier ones, option by option. Routes without - * an override keep the application's options. + * Routes without an override keep the application's options. */ export function createTestRouteTree( routeTree: TRouteTree, - ...overrideMaps: Array + overrides?: AnyRouteTestOverrides, ): TRouteTree { initRouteTree(routeTree) - for (const overrides of overrideMaps) { - if (overrides) { - assertKnownRouteIds(routeTree, Object.keys(overrides)) - } + if (overrides) { + assertKnownRouteIds(routeTree, Object.keys(overrides)) } return cloneRouteTree( routeTree, (route) => { - let patch: RouteOptionsPatch | undefined - for (const overrides of overrideMaps) { - const override = overrides?.[route.id] - if (override) { - patch ??= {} - applyOverride(patch, route.id, override) - } - } - return patch + const override = overrides?.[route.id] + return override ? applyOverride(route.id, override) : undefined }, true, ) diff --git a/packages/router-core/src/testing/types.ts b/packages/router-core/src/testing/types.ts index d766f1d019..bb4d54b3d0 100644 --- a/packages/router-core/src/testing/types.ts +++ b/packages/router-core/src/testing/types.ts @@ -6,9 +6,8 @@ import type { LoaderFnContext, RouteContextOptions, } from '../route' -import type { AllContext, RouteById, RouteIds } from '../routeInfo' -import type { InferRouterContext } from '../router' -import type { Awaitable } from '../utils' +import type { RouteById, RouteIds } from '../routeInfo' +import type { Awaitable, ConstrainLiteral } from '../utils' /** * The component options a test can replace on a route. Framework packages @@ -35,13 +34,6 @@ type OptionalWhenEmpty = ? { [K in TKey]?: TValue } : { [K in TKey]: TValue } -type OptionalWhenUndefined< - TKey extends PropertyKey, - TValue, -> = undefined extends TValue - ? { [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. @@ -96,11 +88,12 @@ export type RouteTestContextFn = ( /** * What a test can replace on one route. Everything is typed from the route. * - * - `beforeLoad`, `loader`: a replacement for that option. - * - `context`: a function replaces the route's `context` option. A value is a - * seed: it stands for everything the route adds to the context, and neither - * the route's `context` option nor its `beforeLoad` runs. - * - `loaderData`: a seed. The route's loader does not run. + * - `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`) @@ -112,11 +105,15 @@ export type RouteTestOverride< > = TComponents & { beforeLoad?: RouteTestBeforeLoadFn loader?: RouteTestLoaderFn + context?: RouteTestContextFn loaderData?: TRoute['types']['loaderData'] - context?: TRoute['types']['routeContext'] | RouteTestContextFn + routeContext?: TRoute['types']['routeContext'] } -/** Overrides by route id. */ +/** + * 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, @@ -127,61 +124,6 @@ export type RouteTestOverrides< > } -/** - * Defaults an application sets once for all of its route tests. - */ -export interface RouterTestingDefaults< - TRouteTree extends AnyRoute, - TComponents = RouteTestComponents, -> { - /** - * Context values every test router starts with. A key given here becomes - * optional in the `context` of each test. - */ - context?: AllContext - /** - * Overrides every test router starts with. A test's own override for a - * route wins, option by option. An isolated route test takes only the - * `loaderData` seeds from here. - */ - routes?: RouteTestOverrides -} - -type DefaultContextKeys = TDefaults extends { - context: infer TContext -} - ? keyof TContext - : never - -type DefaultLoaderDataIds = TDefaults extends { - routes: infer TRoutes -} - ? { - [TId in keyof TRoutes]: TRoutes[TId] extends { loaderData: any } - ? TId - : never - }[keyof TRoutes] - : never - -/** Makes the keys optional that the application's defaults already provide. */ -type WithDefaults = [TValue] extends [ - void | undefined | null, -] - ? TValue - : [TDefaultKeys & keyof TValue] extends [never] - ? TValue - : Omit & - Partial> - -/** The `context` option of a test router: the router context minus the defaults. */ -export type TestRouterContextOption< - TRouteTree extends AnyRoute, - TDefaults = {}, -> = OptionalWhenEmpty< - 'context', - WithDefaults, DefaultContextKeys> -> - type AncestorRoutes = TRoute extends { types: { parentRoute: infer TParentRoute } } @@ -193,46 +135,32 @@ type AncestorRoutes = TRoute extends { : never : never -type RequiresLoaderData< - TRoute extends AnyRoute, - TDefaults, -> = undefined extends TRoute['types']['loaderData'] - ? false - : TRoute['types']['id'] extends DefaultLoaderDataIds - ? false - : true +type BranchRoutes = TRoute | AncestorRoutes -type AncestorLoaderData = { - [TAncestor in AncestorRoutes as RequiresLoaderData< - TAncestor, - TDefaults - > extends true - ? TAncestor['types']['id'] - : never]: { loaderData: TAncestor['types']['loaderData'] } +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'] } & { - [TAncestor in AncestorRoutes as RequiresLoaderData< - TAncestor, - TDefaults - > extends true + [TBranchRoute in BranchRoutes as HasLoaderData extends true ? never - : TAncestor['types']['id']]?: { - loaderData?: TAncestor['types']['loaderData'] - } + : TBranchRoute['types']['id']]?: TBranchRoute['types']['loaderData'] } -type RouteTestStateFor = OptionalWhenEmpty< +type IsolatedRouteStateFor = OptionalWhenEmpty< 'params', TRoute['types']['allParams'] > & OptionalWhenEmpty<'search', TRoute['types']['fullSearchSchemaInput']> & - OptionalWhenEmpty< - 'context', - WithDefaults> - > & - (TRoute['types']['id'] extends DefaultLoaderDataIds - ? { loaderData?: TRoute['types']['loaderData'] } - : OptionalWhenUndefined<'loaderData', TRoute['types']['loaderData']>) & - OptionalWhenEmpty<'routes', AncestorLoaderData> + OptionalWhenEmpty<'context', TRoute['types']['allContext']> & + OptionalWhenEmpty<'loaderData', BranchLoaderData> /** * The state an isolated route test supplies for the route `TId`. No route @@ -241,12 +169,12 @@ type RouteTestStateFor = OptionalWhenEmpty< * * - `params`: all path params of the route. * - `search`: search params, which still go through `validateSearch`. - * - `context`: the merged context of the route, minus the defaults. - * - `loaderData`: the route's loader data. - * - `routes`: loader data of the ancestors whose loader returns something. + * - `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 RouteTestOptions< - TRouteTree extends AnyRoute, - TId, - TDefaults = {}, -> = { route: TId } & RouteTestStateFor, TDefaults> +export type IsolatedRouteState = { + // 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 index d8fe9ac86d..86a40360a0 100644 --- a/packages/router-core/tests/testing.test.ts +++ b/packages/router-core/tests/testing.test.ts @@ -174,12 +174,12 @@ describe('createTestRouteTree', () => { }) }) - test('treats a context value as a seed for everything the route contributes', async () => { + test('takes routeContext as a seed for everything the route contributes', async () => { const { routeTree, calls } = createTree() const router = createRouter( createTestRouteTree(routeTree, { - '/layout/posts/$postId': { context: { scope: 'seeded scope' } }, + '/layout/posts/$postId': { routeContext: { scope: 'seeded scope' } }, }), '/posts/1', ) @@ -223,34 +223,22 @@ describe('createTestRouteTree', () => { expect(calls).toEqual(['root.beforeLoad', 'layout.loader', 'post.onEnter']) }) - test('lets a later override map win, option by option', async () => { - const { routeTree } = createTree() + test('seeds loader data and replaces components', async () => { + const { routeTree, calls } = createTree() const router = createRouter( - createTestRouteTree( - routeTree, - { - '/layout': { loaderData: 'default layout data' }, - '/layout/posts/$postId': { - loader: () => 'default post data', - component: 'default component', - }, - }, - undefined, - { - '/layout/posts/$postId': { loaderData: 'test post data' }, - }, - ), + createTestRouteTree(routeTree, { + '/layout': { loaderData: 'seeded layout data' }, + '/layout/posts/$postId': { component: 'test component' }, + }), '/posts/1', ) await router.load() - expect(getMatch(router, '/layout')?.loaderData).toBe('default layout data') - expect(getMatch(router, '/layout/posts/$postId')?.loaderData).toBe( - 'test post data', - ) + expect(getMatch(router, '/layout')?.loaderData).toBe('seeded layout data') + expect(calls).not.toContain('layout.loader') expect(router.routesById['/layout/posts/$postId']!.options.component).toBe( - 'default component', + 'test component', ) }) @@ -274,7 +262,7 @@ describe('createTestRouteTree', () => { expect(loadLazyRoute).toHaveBeenCalledTimes(2) }) - test('rejects an unknown route id and an ambiguous loader override', () => { + test('rejects an unknown route id and conflicting overrides', () => { const { routeTree } = createTree() expect(() => createTestRouteTree(routeTree, { '/missing': {} })).toThrow( @@ -287,6 +275,32 @@ describe('createTestRouteTree', () => { ).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".', + ) }) }) From ec53e47fdc00658bead78f1cdd9e3f6942470f32 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:12:08 +0100 Subject: [PATCH 5/8] feat(router-core): move route testing into core, add Solid and Vue `createTestRouterWith` and `createIsolatedTestRouterWith` in `@tanstack/router-core/testing` take a framework's `createRouter` and hold the whole implementation, together with the option types `TestRouterOptions` and `IsolatedTestRouterOptions`. `@tanstack/react-router/testing`, `@tanstack/solid-router/testing` and `@tanstack/vue-router/testing` are thin typed wrappers around them. Only the element under test differs: a React element, a function that returns Solid JSX (Solid evaluates JSX right away), or a Vue vnode. Co-Authored-By: Claude Opus 5.5 --- .changeset/router-testing-utilities.md | 6 +- docs/router/api/router.md | 4 +- .../createIsolatedTestRouterFunction.md | 6 +- .../api/router/createTestRouterFunction.md | 9 +- docs/router/config.json | 7 +- docs/router/guide/testing-routes.md | 44 +++- packages/react-router/src/testing.ts | 149 ++--------- packages/router-core/src/testing/index.ts | 8 + packages/router-core/src/testing/router.ts | 118 +++++++++ packages/router-core/src/testing/types.ts | 76 ++++++ packages/router-core/tests/testing.test.ts | 128 +++++++++ packages/solid-router/package.json | 14 + packages/solid-router/src/testing.ts | 165 ++++++++++++ .../solid-router/tests/testing.test-d.tsx | 108 ++++++++ packages/solid-router/tests/testing.test.tsx | 234 +++++++++++++++++ packages/solid-router/vite.config.ts | 1 + packages/vue-router/package.json | 6 + packages/vue-router/src/testing.ts | 166 ++++++++++++ packages/vue-router/tests/testing.test-d.tsx | 102 ++++++++ packages/vue-router/tests/testing.test.tsx | 245 ++++++++++++++++++ packages/vue-router/vite.config.ts | 1 + 21 files changed, 1456 insertions(+), 141 deletions(-) create mode 100644 packages/router-core/src/testing/router.ts create mode 100644 packages/solid-router/src/testing.ts create mode 100644 packages/solid-router/tests/testing.test-d.tsx create mode 100644 packages/solid-router/tests/testing.test.tsx create mode 100644 packages/vue-router/src/testing.ts create mode 100644 packages/vue-router/tests/testing.test-d.tsx create mode 100644 packages/vue-router/tests/testing.test.tsx diff --git a/.changeset/router-testing-utilities.md b/.changeset/router-testing-utilities.md index fa9d9a4e57..4c5b585532 100644 --- a/.changeset/router-testing-utilities.md +++ b/.changeset/router-testing-utilities.md @@ -1,12 +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`. Both return a router to render with `RouterProvider`. +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 framework-independent part is exported from `@tanstack/router-core/testing`. +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 190fed35db..f50ebad032 100644 --- a/docs/router/api/router.md +++ b/docs/router/api/router.md @@ -12,8 +12,8 @@ title: Router API - [`createLazyRoute`](./router/createLazyRouteFunction.md) - [`createRouteMask`](./router/createRouteMaskFunction.md) - [`createRouter`](./router/createRouterFunction.md) - - [`createTestRouter`](./router/createTestRouterFunction.md) (experimental, React only) - - [`createIsolatedTestRouter`](./router/createIsolatedTestRouterFunction.md) (experimental, React only) + - [`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 index 04b9003f30..69ca16654c 100644 --- a/docs/router/api/router/createIsolatedTestRouterFunction.md +++ b/docs/router/api/router/createIsolatedTestRouterFunction.md @@ -3,9 +3,9 @@ id: createIsolatedTestRouterFunction title: createIsolatedTestRouter function --- -> **Experimental:** `createIsolatedTestRouter` is experimental and subject to change. It is available for React only. +> **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 `@tanstack/react-router/testing`. The [Testing Routes guide](../../guide/testing-routes.md) shows how to use it. +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. @@ -27,7 +27,7 @@ The `createIsolatedTestRouter` function accepts the following properties, plus t ### `element` property -- Type: `React.ReactElement` +- 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. diff --git a/docs/router/api/router/createTestRouterFunction.md b/docs/router/api/router/createTestRouterFunction.md index 5e143a2615..dd2f4a0f9c 100644 --- a/docs/router/api/router/createTestRouterFunction.md +++ b/docs/router/api/router/createTestRouterFunction.md @@ -3,9 +3,9 @@ id: createTestRouterFunction title: createTestRouter function --- -> **Experimental:** `createTestRouter` is experimental and subject to change. It is available for React only. +> **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 `@tanstack/react-router/testing`. The [Testing Routes guide](../../guide/testing-routes.md) shows how to use it. +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 @@ -66,10 +66,13 @@ It throws when `overrides` names a route that does not exist, gives a route both ## Framework-independent core -`@tanstack/router-core/testing` holds the parts that do not depend on a framework. Framework packages build on it; apps use `@tanstack/react-router/testing`. +`@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`. | diff --git a/docs/router/config.json b/docs/router/config.json index 501eb94b64..f846f3f514 100644 --- a/docs/router/config.json +++ b/docs/router/config.json @@ -309,7 +309,12 @@ }, { "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 index 71e4dc9aff..d8780cac5c 100644 --- a/docs/router/guide/testing-routes.md +++ b/docs/router/guide/testing-routes.md @@ -3,11 +3,13 @@ id: testing-routes title: Testing Routes --- -> **Experimental:** The route testing utilities are experimental and subject to change. They are available for React only. +> **Experimental:** The route testing utilities are experimental and subject to change. They are available for React, Solid and Vue. -`@tanstack/react-router/testing` creates routers for tests from your app's route tree. 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. +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. -It has two functions. Both return a router that you render with `RouterProvider`, so they work with any test library: +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 | | -------------------------- | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------- | @@ -36,7 +38,7 @@ export default defineConfig({ }) ``` -With code-based routing, pass the route tree you build with `addChildren`. +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 @@ -264,11 +266,41 @@ const router = createTestRouter({ }) ``` -`createIsolatedTestRouter` leaves out `defaultComponent`, `defaultPendingComponent` and `defaultErrorComponent`, and turns off the router's global error boundary, so an error the element throws reaches the test from your `render` call. 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. +`createIsolatedTestRouter` leaves out `defaultComponent`, `defaultPendingComponent` and `defaultErrorComponent`, 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 -- Only React is supported. - 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. diff --git a/packages/react-router/src/testing.ts b/packages/react-router/src/testing.ts index c24b66061d..c58d58de3b 100644 --- a/packages/react-router/src/testing.ts +++ b/packages/react-router/src/testing.ts @@ -1,25 +1,15 @@ -import { createMemoryHistory } from '@tanstack/history' import { - assertIsolatedRouteLoaded, - assertRouteTestParams, - createIsolatedRouteTree, - createTestRouteTree, - setTestRouterLocation, + 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 { - AnyRoute, - RouterConstructorOptions, - RouterOptions, - TrailingSlashOption, - ValidateNavigateOptions, -} from '@tanstack/router-core' -import type { - AnyRouteTestOverrides, RouteTestOverrides as CoreRouteTestOverrides, - IsolatedRouteState, + IsolatedTestRouterOptions, + TestRouterOptions, } from '@tanstack/router-core/testing' import type { ErrorRouteComponent, @@ -50,7 +40,7 @@ export interface RouteTestComponents { export type RouteTestOverrides = CoreRouteTestOverrides -/** The options of `createTestRouter`: those of `createRouter`, plus two. */ +/** The options of `createTestRouter`: those of `createRouter`, plus `location` and `overrides`. */ export type CreateTestRouterOptions< TRouteTree extends AnyRoute, TLocation = unknown, @@ -58,34 +48,15 @@ export type CreateTestRouterOptions< TDefaultStructuralSharingOption extends boolean = false, TRouterHistory extends RouterHistory = RouterHistory, TDehydrated extends Record = Record, -> = RouterConstructorOptions< +> = TestRouterOptions< TRouteTree, + TLocation, TTrailingSlashOption, TDefaultStructuralSharingOption, TRouterHistory, - TDehydrated -> & { - routeTree: TRouteTree - /** - * Where the router starts, typed like the options of `navigate`. It - * replaces the current entry of `history`. Defaults to `/`. - */ - location?: ValidateNavigateOptions< - Router< - TRouteTree, - TTrailingSlashOption, - TDefaultStructuralSharingOption, - TRouterHistory, - TDehydrated - >, - TLocation - > - /** - * Per-route overrides. A route that is not listed keeps the application's - * options. - */ - overrides?: RouteTestOverrides -} + TDehydrated, + RouteTestComponents +> /** The options of `createIsolatedTestRouter`. */ export type CreateIsolatedTestRouterOptions< @@ -93,38 +64,13 @@ export type CreateIsolatedTestRouterOptions< TId, 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: React.ReactElement -} & IsolatedRouteState - -interface AnyCreateTestRouterOptions { - routeTree: AnyRoute - location?: object - overrides?: AnyRouteTestOverrides - history?: RouterHistory -} - -interface AnyCreateIsolatedTestRouterOptions { - routeTree: AnyRoute - element: React.ReactElement - route: string - params?: Record - search?: Record - context?: Record - loaderData?: Record -} +> = IsolatedTestRouterOptions< + TRouteTree, + TId, + React.ReactElement, + TTrailingSlashOption, + TDefaultStructuralSharingOption +> /** * Creates a router for a test, over a copy of the route tree. It takes the @@ -168,19 +114,7 @@ export function createTestRouter< TRouterHistory, TDehydrated > { - const { routeTree, location, overrides, history, ...routerOptions } = - options as AnyCreateTestRouterOptions - const router = createRouter({ - ...routerOptions, - routeTree: createTestRouteTree(routeTree, overrides), - history: history ?? createMemoryHistory(), - } as any) - - if (location) { - setTestRouterLocation(router, location) - } - - return router as any + return createTestRouterWith(createRouter, options as any) as any } /** @@ -203,7 +137,7 @@ export function createTestRouter< * render() * ``` */ -export async function createIsolatedTestRouter< +export function createIsolatedTestRouter< TRouteTree extends AnyRoute, // `IsolatedRouteState` checks that `route` is a route id of the tree. const TId extends string, @@ -219,42 +153,9 @@ export async function createIsolatedTestRouter< ): Promise< Router > { - const { - routeTree, - element, - route, - params, - search, - context, - loaderData, - ...routerOptions - } = options as unknown as AnyCreateIsolatedTestRouterOptions - - const router = createRouter({ - ...routerOptions, - // Nothing of the application renders around the element, and an error - // it throws reaches the test instead of an error component. - defaultComponent: undefined, - defaultErrorComponent: undefined, - defaultPendingComponent: undefined, - disableGlobalCatchBoundary: true, - routeTree: createIsolatedRouteTree(routeTree, { - routeId: route, - component: () => element, - loaderData: new Map(Object.entries(loaderData ?? {})), - }), - history: createMemoryHistory(), - context, - } as any) - - assertRouteTestParams(router, route, params) - setTestRouterLocation(router, { - to: router.routesById[route]!.fullPath, - params, - search, - }) - await router.load() - assertIsolatedRouteLoaded(router, route) - - return router as any + const { element, ...state } = options as any + return createIsolatedTestRouterWith(createRouter, { + ...state, + component: () => element, + }) as any } diff --git a/packages/router-core/src/testing/index.ts b/packages/router-core/src/testing/index.ts index 2b4181e502..00d944b254 100644 --- a/packages/router-core/src/testing/index.ts +++ b/packages/router-core/src/testing/index.ts @@ -1,3 +1,9 @@ +export { createIsolatedTestRouterWith, createTestRouterWith } from './router' +export type { + AnyIsolatedTestRouterOptions, + AnyTestRouterOptions, + TestRouterFactory, +} from './router' export { assertIsolatedRouteLoaded, assertRouteTestParams, @@ -13,10 +19,12 @@ export type { } from './routeTree' export type { IsolatedRouteState, + IsolatedTestRouterOptions, RouteTestBeforeLoadFn, RouteTestComponents, RouteTestContextFn, RouteTestLoaderFn, RouteTestOverride, RouteTestOverrides, + TestRouterOptions, } from './types' diff --git a/packages/router-core/src/testing/router.ts b/packages/router-core/src/testing/router.ts new file mode 100644 index 0000000000..90758485c3 --- /dev/null +++ b/packages/router-core/src/testing/router.ts @@ -0,0 +1,118 @@ +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 +} + +/** + * 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 { + 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 { + 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, + 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 index bb4d54b3d0..fe14a330ed 100644 --- a/packages/router-core/src/testing/types.ts +++ b/packages/router-core/src/testing/types.ts @@ -1,3 +1,4 @@ +import type { RouterHistory } from '@tanstack/history' import type { AnyRoute, BeforeLoadContextOptions, @@ -7,6 +8,13 @@ import type { 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' /** @@ -178,3 +186,71 @@ export type IsolatedRouteState = { // TypeScript widens a constant such as `rootRouteId` while inferring. route: ConstrainLiteral> } & 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`. Defaults to `/`. + */ + 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 +} + +/** + * 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 +} & IsolatedRouteState diff --git a/packages/router-core/tests/testing.test.ts b/packages/router-core/tests/testing.test.ts index 86a40360a0..c760638db6 100644 --- a/packages/router-core/tests/testing.test.ts +++ b/packages/router-core/tests/testing.test.ts @@ -5,7 +5,9 @@ import { assertIsolatedRouteLoaded, assertRouteTestParams, createIsolatedRouteTree, + createIsolatedTestRouterWith, createTestRouteTree, + createTestRouterWith, initRouteTree, setTestRouterLocation, } from '../src/testing' @@ -444,3 +446,129 @@ describe('helpers for a test router', () => { ) }) }) + +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', + }) + + 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', + ) + // A framework option, so core types do not know it. + expect( + (router.options as Record).defaultComponent, + ).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', + }), + ).rejects.toThrow('The route "/layout" is not matched at "/"') + }) +}) 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..c59bbb508e --- /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, + // `IsolatedRouteState` 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..1ed802f0a0 --- /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, + // `IsolatedRouteState` 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, From e1bbf1da0bf526d0d2eddd5d4d99f4b28d850cf2 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:29:59 +0100 Subject: [PATCH 6/8] test(vue-router): add a route-testing e2e project The same app and tests as `e2e/react-router/route-testing`, written with Vue JSX: file-based routes with automatic code splitting, tested through `@tanstack/vue-router/testing` with Vitest in jsdom, including type tests. The Solid counterpart is held back: under pnpm, vite-plugin-solid injects a jest-dom setup file into projects that do not depend on jest-dom, because its check also searches the NODE_PATH that pnpm's bin shims set. Co-Authored-By: Claude Opus 5.5 --- e2e/vue-router/route-testing/.gitignore | 4 + e2e/vue-router/route-testing/package.json | 20 +++ e2e/vue-router/route-testing/src/api.ts | 35 ++++ .../src/components/PostHeader.tsx | 32 ++++ .../route-testing/src/components/UserMenu.tsx | 19 +++ .../route-testing/src/routeTree.gen.ts | 119 ++++++++++++++ e2e/vue-router/route-testing/src/router.tsx | 16 ++ .../route-testing/src/routes/__root.tsx | 25 +++ .../route-testing/src/routes/_authed.tsx | 26 +++ .../src/routes/_authed/posts.$postId.tsx | 38 +++++ .../route-testing/src/routes/index.tsx | 19 +++ .../route-testing/src/routes/login.tsx | 26 +++ .../route-testing/src/test-fixtures.ts | 20 +++ .../route-testing/tests/post-header.test.tsx | 118 ++++++++++++++ .../route-testing/tests/post-route.test.tsx | 154 ++++++++++++++++++ .../tests/route-testing.test-d.tsx | 136 ++++++++++++++++ e2e/vue-router/route-testing/tests/setup.ts | 11 ++ .../route-testing/tests/user-menu.test.tsx | 62 +++++++ e2e/vue-router/route-testing/tsconfig.json | 16 ++ e2e/vue-router/route-testing/vite.config.ts | 23 +++ pnpm-lock.yaml | 75 ++++++--- 21 files changed, 968 insertions(+), 26 deletions(-) create mode 100644 e2e/vue-router/route-testing/.gitignore create mode 100644 e2e/vue-router/route-testing/package.json create mode 100644 e2e/vue-router/route-testing/src/api.ts create mode 100644 e2e/vue-router/route-testing/src/components/PostHeader.tsx create mode 100644 e2e/vue-router/route-testing/src/components/UserMenu.tsx create mode 100644 e2e/vue-router/route-testing/src/routeTree.gen.ts create mode 100644 e2e/vue-router/route-testing/src/router.tsx create mode 100644 e2e/vue-router/route-testing/src/routes/__root.tsx create mode 100644 e2e/vue-router/route-testing/src/routes/_authed.tsx create mode 100644 e2e/vue-router/route-testing/src/routes/_authed/posts.$postId.tsx create mode 100644 e2e/vue-router/route-testing/src/routes/index.tsx create mode 100644 e2e/vue-router/route-testing/src/routes/login.tsx create mode 100644 e2e/vue-router/route-testing/src/test-fixtures.ts create mode 100644 e2e/vue-router/route-testing/tests/post-header.test.tsx create mode 100644 e2e/vue-router/route-testing/tests/post-route.test.tsx create mode 100644 e2e/vue-router/route-testing/tests/route-testing.test-d.tsx create mode 100644 e2e/vue-router/route-testing/tests/setup.ts create mode 100644 e2e/vue-router/route-testing/tests/user-menu.test.tsx create mode 100644 e2e/vue-router/route-testing/tsconfig.json create mode 100644 e2e/vue-router/route-testing/vite.config.ts 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/pnpm-lock.yaml b/pnpm-lock.yaml index bf4c0bb5df..a64e1f009e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6881,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': @@ -14959,7 +14987,7 @@ importers: 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) vite-plugin-solid: specifier: ^2.11.10 || ^3.0.0-0 - version: 2.11.16(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(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)) + version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(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)) zod: specifier: 'catalog:' version: 4.5.4 @@ -29074,16 +29102,6 @@ packages: '@testing-library/jest-dom': optional: true - vite-plugin-solid@2.11.16: - resolution: {integrity: sha512-qguFUmqY2ICuoGHrZjm+cWpvKkqVyWDMptipC/BIEGr9q6wEzwTWYOjM9pEWJ+yoTuF6T5OpysI2Okdy7rsVlQ==} - peerDependencies: - '@testing-library/jest-dom': ^5.16.6 || ^5.17.0 || ^6.0.0 || ^7.0.0 - solid-js: 1.9.12 - vite: ^8.3.4 - peerDependenciesMeta: - '@testing-library/jest-dom': - optional: true - vite-tsconfig-paths@6.1.1: resolution: {integrity: sha512-2cihq7zliibCCZ8P9cKJrQBkfgdvcFkOOc3Y02o3GWUDLgqjWsZudaoiuOwO/gzTzy17cS5F7ZPo4bsnS4DGkg==} peerDependencies: @@ -35776,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) @@ -36678,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) @@ -44070,21 +44108,6 @@ snapshots: transitivePeerDependencies: - supports-color - vite-plugin-solid@2.11.16(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(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)): - dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) - '@types/babel__core': 7.20.5 - babel-preset-solid: 1.9.10(@babel/core@7.29.7(supports-color@10.2.2))(solid-js@1.9.12) - merge-anything: 5.1.7 - solid-js: 1.9.12 - solid-refresh: 0.6.3(solid-js@1.9.12)(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) - 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)) - optionalDependencies: - '@testing-library/jest-dom': 6.6.3 - transitivePeerDependencies: - - supports-color - vite-tsconfig-paths@6.1.1(@typescript/typescript6@6.0.2)(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.27.4)(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: debug: 4.4.3(supports-color@10.2.2) From 59120770a3f0143068db5ae70c9e5b9d43772c7f Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:04:03 +0100 Subject: [PATCH 7/8] fix(router): address review of the route testing utilities - initRouteTree initialises the whole tree every time, as a router does. It skipped a tree whose root already had an id, so a route added later with `addChildren` stayed uninitialised and an override for it was rejected as unknown. - createIsolatedTestRouter also leaves out defaultNotFoundComponent. After the element navigated to a location without a route, the router rendered the app's not-found component. - IsolatedRouteState types `route` as `TId`; it accepted every route id. The ConstrainLiteral check, which keeps `rootRouteId` from widening during inference, moves to the options of createIsolatedTestRouter. - The docs say where createTestRouter starts without `location`: at the current location of its history, which is `/` for the default memory history. Co-Authored-By: Claude Opus 5.5 --- .../createIsolatedTestRouterFunction.md | 2 +- .../api/router/createTestRouterFunction.md | 2 +- docs/router/guide/testing-routes.md | 4 +-- packages/react-router/src/testing.ts | 2 +- .../react-router/tests/testing.test-d.tsx | 7 +++- packages/react-router/tests/testing.test.tsx | 21 ++++++++++++ packages/router-core/src/testing/routeTree.ts | 14 +++----- packages/router-core/src/testing/router.ts | 1 + packages/router-core/src/testing/types.ts | 17 ++++++---- packages/router-core/tests/testing.test.ts | 34 ++++++++++++------- packages/solid-router/src/testing.ts | 2 +- packages/vue-router/src/testing.ts | 2 +- 12 files changed, 73 insertions(+), 35 deletions(-) diff --git a/docs/router/api/router/createIsolatedTestRouterFunction.md b/docs/router/api/router/createIsolatedTestRouterFunction.md index 69ca16654c..046279ae3c 100644 --- a/docs/router/api/router/createIsolatedTestRouterFunction.md +++ b/docs/router/api/router/createIsolatedTestRouterFunction.md @@ -11,7 +11,7 @@ No `context`, `beforeLoad` or `loader` option of any route runs, no route compon ## createIsolatedTestRouter options -The `createIsolatedTestRouter` function accepts the following properties, plus the [`RouterOptions`](./RouterOptionsType.md) that [`createRouter`](./createRouterFunction.md) accepts, except `history`, `context` and `search`. It leaves out `defaultComponent`, `defaultPendingComponent` and `defaultErrorComponent`, and sets `disableGlobalCatchBoundary`. +The `createIsolatedTestRouter` function accepts the following properties, plus the [`RouterOptions`](./RouterOptionsType.md) that [`createRouter`](./createRouterFunction.md) accepts, except `history`, `context` and `search`. It leaves out `defaultComponent`, `defaultPendingComponent`, `defaultErrorComponent` and `defaultNotFoundComponent`, and sets `disableGlobalCatchBoundary`. ### `routeTree` property diff --git a/docs/router/api/router/createTestRouterFunction.md b/docs/router/api/router/createTestRouterFunction.md index dd2f4a0f9c..8c776f00c2 100644 --- a/docs/router/api/router/createTestRouterFunction.md +++ b/docs/router/api/router/createTestRouterFunction.md @@ -21,7 +21,7 @@ The `createTestRouter` function accepts the [`RouterOptions`](./RouterOptionsTyp - Type: [`NavigateOptions`](./NavigateOptionsType.md), checked against the route tree - Optional -- Where the router starts. It replaces the current entry of the router's history. Defaults to `/`. +- 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 diff --git a/docs/router/guide/testing-routes.md b/docs/router/guide/testing-routes.md index d8780cac5c..f4a5c35ac6 100644 --- a/docs/router/guide/testing-routes.md +++ b/docs/router/guide/testing-routes.md @@ -117,7 +117,7 @@ test('sends a signed-out visitor to the login page', async () => { 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 `/`. +- `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. @@ -266,7 +266,7 @@ const router = createTestRouter({ }) ``` -`createIsolatedTestRouter` leaves out `defaultComponent`, `defaultPendingComponent` and `defaultErrorComponent`, 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. +`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 diff --git a/packages/react-router/src/testing.ts b/packages/react-router/src/testing.ts index c58d58de3b..31a501e044 100644 --- a/packages/react-router/src/testing.ts +++ b/packages/react-router/src/testing.ts @@ -139,7 +139,7 @@ export function createTestRouter< */ export function createIsolatedTestRouter< TRouteTree extends AnyRoute, - // `IsolatedRouteState` checks that `route` is a route id of the tree. + // `IsolatedTestRouterOptions` checks that `route` is a route id of the tree. const TId extends string, TTrailingSlashOption extends TrailingSlashOption = 'never', TDefaultStructuralSharingOption extends boolean = false, diff --git a/packages/react-router/tests/testing.test-d.tsx b/packages/react-router/tests/testing.test-d.tsx index 0a336a7878..3e9b83dac9 100644 --- a/packages/react-router/tests/testing.test-d.tsx +++ b/packages/react-router/tests/testing.test-d.tsx @@ -76,7 +76,7 @@ describe('createIsolatedTestRouter', () => { expectTypeOf>().toEqualTypeOf< 'route' | 'params' | 'context' | 'loaderData' >() - expectTypeOf<'/_authed/posts/$postId'>().toExtend() + expectTypeOf().toEqualTypeOf<'/_authed/posts/$postId'>() expectTypeOf().toEqualTypeOf<'postId'>() expectTypeOf().toEqualTypeOf() expectTypeOf().toEqualTypeOf< @@ -116,6 +116,11 @@ describe('createIsolatedTestRouter', () => { 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', () => { diff --git a/packages/react-router/tests/testing.test.tsx b/packages/react-router/tests/testing.test.tsx index 75c8c8562c..f64a63176f 100644 --- a/packages/react-router/tests/testing.test.tsx +++ b/packages/react-router/tests/testing.test.tsx @@ -561,6 +561,27 @@ describe('createIsolatedTestRouter', () => { 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(() => {}) diff --git a/packages/router-core/src/testing/routeTree.ts b/packages/router-core/src/testing/routeTree.ts index 2e7388204e..446c9992ab 100644 --- a/packages/router-core/src/testing/routeTree.ts +++ b/packages/router-core/src/testing/routeTree.ts @@ -68,15 +68,13 @@ function getChildren(route: AnyRoute): 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. 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. + * 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 { - if ((routeTree.id as string | undefined) !== undefined) { - return - } let index = 0 const visit = (route: AnyRoute) => { route.init(index++) @@ -90,8 +88,6 @@ function cloneRouteTree( getPatch: (route: AnyRoute) => RouteOptionsPatch | undefined, keepLazyRoutes: boolean, ): TRouteTree { - initRouteTree(routeTree) - const cloneRoute = (route: AnyRoute, parent?: AnyRoute): AnyRoute => { const patch = getPatch(route) // Route classes take all their state from `options`, so a fresh instance diff --git a/packages/router-core/src/testing/router.ts b/packages/router-core/src/testing/router.ts index 90758485c3..fe2297ab08 100644 --- a/packages/router-core/src/testing/router.ts +++ b/packages/router-core/src/testing/router.ts @@ -95,6 +95,7 @@ export async function createIsolatedTestRouterWith( defaultComponent: undefined, defaultErrorComponent: undefined, defaultPendingComponent: undefined, + defaultNotFoundComponent: undefined, disableGlobalCatchBoundary: true, routeTree: createIsolatedRouteTree(routeTree, { routeId: route, diff --git a/packages/router-core/src/testing/types.ts b/packages/router-core/src/testing/types.ts index fe14a330ed..14dad3b41e 100644 --- a/packages/router-core/src/testing/types.ts +++ b/packages/router-core/src/testing/types.ts @@ -181,10 +181,11 @@ type IsolatedRouteStateFor = OptionalWhenEmpty< * - `loaderData`: loader data by route id, for the route and the routes above * it whose loader returns data. */ -export type IsolatedRouteState = { - // Checked here rather than in a constraint on `TId`: with a constraint, - // TypeScript widens a constant such as `rootRouteId` while inferring. - route: ConstrainLiteral> +export type IsolatedRouteState< + TRouteTree extends AnyRoute, + TId extends RouteIds, +> = { + route: TId } & IsolatedRouteStateFor> /** @@ -210,7 +211,8 @@ export type TestRouterOptions< routeTree: TRouteTree /** * Where the router starts, typed like the options of `navigate`. It - * replaces the current entry of `history`. Defaults to `/`. + * 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< @@ -253,4 +255,7 @@ export type IsolatedTestRouterOptions< routeTree: TRouteTree /** The element under test. It renders in place of the route's component. */ element: TElement -} & IsolatedRouteState + // 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 index c760638db6..d27d53b688 100644 --- a/packages/router-core/tests/testing.test.ts +++ b/packages/router-core/tests/testing.test.ts @@ -113,16 +113,25 @@ describe('initRouteTree', () => { expect(postRoute.parentRoute).toBe(layoutRoute) }) - test('leaves a tree alone that a router has already processed', () => { - const { routeTree, postRoute } = createTree() + test('initialises routes added to a tree that a router has processed', () => { + const { routeTree, rootRoute } = createTree() createRouter(routeTree, '/') - const originalIndex = postRoute.originalIndex - const init = vi.spyOn(postRoute, 'init') + const aboutRoute = new BaseRoute({ + getParentRoute: () => rootRoute, + path: '/about', + }) + rootRoute.addChildren([ + ...(rootRoute.children as Array), + aboutRoute, + ]) - initRouteTree(routeTree) - - expect(init).not.toHaveBeenCalled() - expect(postRoute.originalIndex).toBe(originalIndex) + expect(() => + createTestRouteTree(routeTree, { + '/about': { loaderData: 'seeded about data' }, + }), + ).not.toThrow() + expect(aboutRoute.id).toBe('/about') + expect(aboutRoute.to).toBe('/about') }) }) @@ -516,6 +525,7 @@ describe('createIsolatedTestRouterWith', () => { '/layout/posts/$postId': 'seeded post data', }, defaultComponent: 'default component', + defaultNotFoundComponent: 'default not-found component', }) expect(calls).toEqual([]) @@ -531,10 +541,10 @@ describe('createIsolatedTestRouterWith', () => { expect(routes['/layout/posts/$postId']!.options.component).toBe( 'element under test', ) - // A framework option, so core types do not know it. - expect( - (router.options as Record).defaultComponent, - ).toBeUndefined() + // 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) }) diff --git a/packages/solid-router/src/testing.ts b/packages/solid-router/src/testing.ts index c59bbb508e..5c023a8800 100644 --- a/packages/solid-router/src/testing.ts +++ b/packages/solid-router/src/testing.ts @@ -142,7 +142,7 @@ export function createTestRouter< */ export function createIsolatedTestRouter< TRouteTree extends AnyRoute, - // `IsolatedRouteState` checks that `route` is a route id of the tree. + // `IsolatedTestRouterOptions` checks that `route` is a route id of the tree. const TId extends string, TTrailingSlashOption extends TrailingSlashOption = 'never', TDefaultStructuralSharingOption extends boolean = false, diff --git a/packages/vue-router/src/testing.ts b/packages/vue-router/src/testing.ts index 1ed802f0a0..2d9739fb5d 100644 --- a/packages/vue-router/src/testing.ts +++ b/packages/vue-router/src/testing.ts @@ -143,7 +143,7 @@ export function createTestRouter< */ export function createIsolatedTestRouter< TRouteTree extends AnyRoute, - // `IsolatedRouteState` checks that `route` is a route id of the tree. + // `IsolatedTestRouterOptions` checks that `route` is a route id of the tree. const TId extends string, TTrailingSlashOption extends TrailingSlashOption = 'never', TDefaultStructuralSharingOption extends boolean = false, From 75637991a3c6679276ecb9ef26b1a76d7067b065 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:34:23 +0100 Subject: [PATCH 8/8] fix(router): reject notFoundRoute and explain not-found rejections - Neither test router supports the deprecated `notFoundRoute` option. The option types declare it as `never`, and both functions throw when it is passed anyway. In `createIsolatedTestRouter` it rendered the app's not-found route after a navigation, and the root used it to catch a `notFound()` thrown by the element, which then crashed. - When `params.parse` threw `notFound()`, `createIsolatedTestRouter` rejected with "is not matched", although the route was matched with a not-found. When `validateSearch` threw it, the router wraps it in a `SearchParamError` without a message, so the rejection had none. Both now name the route and the step that threw. Co-Authored-By: Claude Opus 5.5 --- .../createIsolatedTestRouterFunction.md | 4 +-- .../api/router/createTestRouterFunction.md | 2 +- docs/router/guide/testing-routes.md | 4 ++- packages/router-core/src/testing/routeTree.ts | 25 +++++++++++++-- packages/router-core/src/testing/router.ts | 10 ++++++ packages/router-core/src/testing/types.ts | 10 ++++++ packages/router-core/tests/testing.test.ts | 32 ++++++++++++++++++- 7 files changed, 79 insertions(+), 8 deletions(-) diff --git a/docs/router/api/router/createIsolatedTestRouterFunction.md b/docs/router/api/router/createIsolatedTestRouterFunction.md index 046279ae3c..a3b9ab32cc 100644 --- a/docs/router/api/router/createIsolatedTestRouterFunction.md +++ b/docs/router/api/router/createIsolatedTestRouterFunction.md @@ -11,7 +11,7 @@ No `context`, `beforeLoad` or `loader` option of any route runs, no route compon ## createIsolatedTestRouter options -The `createIsolatedTestRouter` function accepts the following properties, plus the [`RouterOptions`](./RouterOptionsType.md) that [`createRouter`](./createRouterFunction.md) accepts, except `history`, `context` and `search`. It leaves out `defaultComponent`, `defaultPendingComponent`, `defaultErrorComponent` and `defaultNotFoundComponent`, and sets `disableGlobalCatchBoundary`. +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 @@ -56,7 +56,7 @@ The `createIsolatedTestRouter` function accepts the following properties, plus t - 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 `validateSearch` rejects the search params), and when the location of `route` does not lead to it, as for a pathless layout route. +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 diff --git a/docs/router/api/router/createTestRouterFunction.md b/docs/router/api/router/createTestRouterFunction.md index 8c776f00c2..ba578e1f89 100644 --- a/docs/router/api/router/createTestRouterFunction.md +++ b/docs/router/api/router/createTestRouterFunction.md @@ -9,7 +9,7 @@ The `createTestRouter` function creates a [`Router`](./RouterType.md) for a test ## createTestRouter options -The `createTestRouter` function accepts the [`RouterOptions`](./RouterOptionsType.md) that [`createRouter`](./createRouterFunction.md) accepts, plus the following properties. +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 diff --git a/docs/router/guide/testing-routes.md b/docs/router/guide/testing-routes.md index f4a5c35ac6..ec3d608b7b 100644 --- a/docs/router/guide/testing-routes.md +++ b/docs/router/guide/testing-routes.md @@ -223,7 +223,7 @@ 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, +- 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 @@ -266,6 +266,8 @@ const router = createTestRouter({ }) ``` +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 diff --git a/packages/router-core/src/testing/routeTree.ts b/packages/router-core/src/testing/routeTree.ts index 446c9992ab..0f4de1092d 100644 --- a/packages/router-core/src/testing/routeTree.ts +++ b/packages/router-core/src/testing/routeTree.ts @@ -1,4 +1,5 @@ import { SEGMENT_TYPE_PARAM } from '../new-process-route-tree' +import { isNotFound } from '../not-found' import type { AnyRoute } from '../route' import type { AnyRouter } from '../router' @@ -293,9 +294,10 @@ export function assertRouteTestParams( } /** - * Throws when an isolated route test did not end up where the test asked: - * the target route is not matched, or a match failed, for example because - * the search params did not pass the route's `validateSearch`. + * 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, @@ -305,7 +307,24 @@ export function assertIsolatedRouteLoaded( 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( diff --git a/packages/router-core/src/testing/router.ts b/packages/router-core/src/testing/router.ts index fe2297ab08..f416914c0e 100644 --- a/packages/router-core/src/testing/router.ts +++ b/packages/router-core/src/testing/router.ts @@ -38,6 +38,14 @@ export interface AnyIsolatedTestRouterOptions { [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. @@ -50,6 +58,7 @@ export function createTestRouterWith( createRouter: TestRouterFactory, options: AnyTestRouterOptions, ): TRouter { + assertNoNotFoundRoute(options.notFoundRoute) const { routeTree, location, overrides, history, ...routerOptions } = options const router = createRouter({ ...routerOptions, @@ -77,6 +86,7 @@ export async function createIsolatedTestRouterWith( createRouter: TestRouterFactory, options: AnyIsolatedTestRouterOptions, ): Promise { + assertNoNotFoundRoute(options.notFoundRoute) const { routeTree, component, diff --git a/packages/router-core/src/testing/types.ts b/packages/router-core/src/testing/types.ts index 14dad3b41e..72711605c2 100644 --- a/packages/router-core/src/testing/types.ts +++ b/packages/router-core/src/testing/types.ts @@ -229,6 +229,11 @@ export type TestRouterOptions< * options. */ overrides?: RouteTestOverrides + /** + * Not supported: the option is deprecated. Give the root route a + * `notFoundComponent` instead. + */ + notFoundRoute?: never } /** @@ -255,6 +260,11 @@ export type IsolatedTestRouterOptions< 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> diff --git a/packages/router-core/tests/testing.test.ts b/packages/router-core/tests/testing.test.ts index d27d53b688..6b052a6bc3 100644 --- a/packages/router-core/tests/testing.test.ts +++ b/packages/router-core/tests/testing.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test, vi } from 'vitest' import { createMemoryHistory } from '@tanstack/history' -import { BaseRootRoute, BaseRoute } from '../src' +import { BaseRootRoute, BaseRoute, notFound } from '../src' import { assertIsolatedRouteLoaded, assertRouteTestParams, @@ -42,10 +42,21 @@ function createTree() { 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: () => { @@ -574,6 +585,25 @@ describe('createIsolatedTestRouterWith', () => { 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,