= []
+ 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: () => (
+
+ ),
+ })
+
+ 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: () => (
+
+ ),
+ })
+
+ 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 (
+
+ )
+ }
+
+ const loginRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: '/login',
+ component: () => Login page
,
+ })
+
+ const lazyRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: '/lazy',
+ }).lazy(loadLazyRoute)
+
+ const indexRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: '/',
+ component: () => Home page
,
+ })
+
+ const routeTree = rootRoute.addChildren([
+ authedRoute.addChildren([postRoute]),
+ loginRoute,
+ lazyRoute,
+ indexRoute,
+ ])
+
+ return {
+ routeTree,
+ authedRoute,
+ postRoute,
+ PostHeader,
+ calls,
+ loadLazyRoute,
+ }
+}
+
+const seededContext = {
+ locale: 'en',
+ session: { user: testUser },
+ user: testUser,
+ scope: 'seeded scope',
+}
+
+describe('createTestRouter', () => {
+ test('runs the lifecycle of the application by default', async () => {
+ const app = createApp()
+
+ const router = createTestRouter({
+ routeTree: app.routeTree,
+ location: { to: '/posts/$postId', params: { postId: '1' } },
+ context: { locale: 'en' },
+ })
+ render()
+
+ expect(
+ await screen.findByText(
+ 'Real user reads post 1 in en on tab details with 1 unread in real scope',
+ ),
+ ).toBeInTheDocument()
+ expect(screen.getByText('App shell')).toBeInTheDocument()
+ expect(screen.getByText('Authed layout')).toBeInTheDocument()
+ expect(app.calls).toEqual([
+ 'root.beforeLoad',
+ 'authed.beforeLoad',
+ 'post.context',
+ 'authed.loader',
+ 'post.loader',
+ ])
+ })
+
+ test('replaces the options a test names and keeps the rest', async () => {
+ const app = createApp()
+
+ const router = createTestRouter({
+ routeTree: app.routeTree,
+ location: {
+ to: '/posts/$postId',
+ params: { postId: '2' },
+ search: { tab: 'comments' },
+ },
+ context: { locale: 'de' },
+ overrides: {
+ [rootRouteId]: { routeContext: { session: { user: testUser } } },
+ '/_authed': { loaderData: { unreadCount: 7 } },
+ '/_authed/posts/$postId': {
+ loader: ({ params }) => ({
+ post: { id: params.postId, title: 'Replaced post' },
+ }),
+ },
+ },
+ })
+ render()
+
+ expect(
+ await screen.findByText(
+ 'Test user reads post 2 in de on tab comments with 7 unread in real scope',
+ ),
+ ).toBeInTheDocument()
+ expect(screen.getByRole('heading')).toHaveTextContent('Replaced post')
+ // The seed for the root route replaced its beforeLoad. The beforeLoad of
+ // `/_authed` was not named, so the real one derived the user.
+ expect(app.calls).toEqual(['authed.beforeLoad', 'post.context'])
+ })
+
+ test('replaces beforeLoad, the context option and components', async () => {
+ const app = createApp()
+
+ const router = createTestRouter({
+ routeTree: app.routeTree,
+ location: { to: '/posts/$postId', params: { postId: '1' } },
+ context: { locale: 'en' },
+ overrides: {
+ '/_authed': {
+ beforeLoad: ({ context }) => ({
+ user: { id: 'derived', name: `Derived in ${context.locale}` },
+ }),
+ component: () => ,
+ },
+ '/_authed/posts/$postId': {
+ context: () => ({ scope: 'test scope' }),
+ component: () => {
+ const context = app.postRoute.useRouteContext()
+ return {`${context.user.name} with ${context.scope}`}
+ },
+ },
+ },
+ })
+ render()
+
+ expect(
+ await screen.findByText('Derived in en with test scope'),
+ ).toBeInTheDocument()
+ expect(screen.getByText('App shell')).toBeInTheDocument()
+ expect(screen.queryByText('Authed layout')).not.toBeInTheDocument()
+ expect(app.calls).toEqual([
+ 'root.beforeLoad',
+ 'authed.loader',
+ 'post.loader',
+ ])
+ })
+
+ test('removes an option that is overridden with undefined', async () => {
+ const app = createApp()
+
+ const router = createTestRouter({
+ routeTree: app.routeTree,
+ location: { to: '/posts/$postId', params: { postId: '1' } },
+ context: { locale: 'en' },
+ overrides: { '/_authed': { loader: undefined } },
+ })
+ await router.load()
+
+ expect(app.calls).not.toContain('authed.loader')
+ expect(
+ router.state.matches.find((match) => match.routeId === '/_authed')
+ ?.loaderData,
+ ).toBeUndefined()
+ })
+
+ test('keeps overrides out of the route tree and out of the next router', async () => {
+ const app = createApp()
+ const originalLoader = app.postRoute.options.loader
+
+ const first = createTestRouter({
+ routeTree: app.routeTree,
+ location: { to: '/posts/$postId', params: { postId: '1' } },
+ context: { locale: 'en' },
+ overrides: {
+ '/_authed/posts/$postId': {
+ loaderData: { post: { id: '1', title: 'Seeded post' } },
+ },
+ },
+ })
+ await first.load()
+ expect(first.state.matches.at(-1)?.loaderData).toEqual({
+ post: { id: '1', title: 'Seeded post' },
+ })
+ expect(app.postRoute.options.loader).toBe(originalLoader)
+
+ const second = createTestRouter({
+ routeTree: app.routeTree,
+ location: { to: '/posts/$postId', params: { postId: '1' } },
+ context: { locale: 'en' },
+ })
+ await second.load()
+ expect(second.state.matches.at(-1)?.loaderData).toEqual({
+ post: { id: '1', title: 'Real post' },
+ })
+ })
+
+ test('initialises the route objects that application code imports', () => {
+ const app = createApp()
+ expect(app.postRoute.id).toBeUndefined()
+
+ createTestRouter({ routeTree: app.routeTree, context: { locale: 'en' } })
+
+ expect(app.postRoute.id).toBe('/_authed/posts/$postId')
+ expect(app.postRoute.fullPath).toBe('/posts/$postId')
+ expect(app.postRoute.to).toBe('/posts/$postId')
+ expect(app.authedRoute.id).toBe('/_authed')
+ })
+
+ test('uses a memory history, or the history it is given', async () => {
+ const app = createApp()
+
+ const withMemoryHistory = createTestRouter({
+ routeTree: app.routeTree,
+ context: { locale: 'en' },
+ })
+ expect(withMemoryHistory.history.location.pathname).toBe('/')
+ expect(window.location.pathname).toBe('/')
+
+ const router = createTestRouter({
+ routeTree: app.routeTree,
+ history: createMemoryHistory({ initialEntries: ['/login'] }),
+ context: { locale: 'en' },
+ })
+ render()
+
+ expect(await screen.findByText('Login page')).toBeInTheDocument()
+ })
+
+ test('passes the other options to the router', async () => {
+ const app = createApp()
+
+ const router = createTestRouter({
+ routeTree: app.routeTree,
+ context: { locale: 'en' },
+ location: { to: '/login' },
+ Wrap: ({ children }) => (
+
+ ),
+ })
+ render()
+
+ expect(await screen.findByLabelText('Providers')).toHaveTextContent(
+ 'Login page',
+ )
+ })
+
+ test('lets an override win over the options of a lazy route', async () => {
+ const app = createApp()
+
+ const real = createTestRouter({
+ routeTree: app.routeTree,
+ location: { to: '/lazy' },
+ context: { locale: 'en' },
+ })
+ const { unmount } = render()
+ expect(await screen.findByText('Lazy component')).toBeInTheDocument()
+ unmount()
+
+ const overridden = createTestRouter({
+ routeTree: app.routeTree,
+ location: { to: '/lazy' },
+ context: { locale: 'en' },
+ overrides: { '/lazy': { component: () => Test component
} },
+ })
+ render()
+ expect(await screen.findByText('Test component')).toBeInTheDocument()
+ expect(screen.queryByText('Lazy component')).not.toBeInTheDocument()
+ })
+
+ test('rejects an override for a route that does not exist', () => {
+ const app = createApp()
+
+ expect(() =>
+ createTestRouter({
+ routeTree: app.routeTree,
+ context: { locale: 'en' },
+ // @ts-expect-error not a route id of this tree
+ overrides: { '/missing': { component: () => null } },
+ }),
+ ).toThrow('The route "/missing" does not exist in the route tree')
+ })
+
+ test('rejects conflicting overrides', () => {
+ const app = createApp()
+
+ expect(() =>
+ createTestRouter({
+ routeTree: app.routeTree,
+ context: { locale: 'en' },
+ overrides: {
+ '/_authed': {
+ loader: () => ({ unreadCount: 1 }),
+ loaderData: { unreadCount: 2 },
+ },
+ },
+ }),
+ ).toThrow('has both "loader" and "loaderData"')
+
+ expect(() =>
+ createTestRouter({
+ routeTree: app.routeTree,
+ context: { locale: 'en' },
+ overrides: {
+ '/_authed': {
+ beforeLoad: () => ({ user: testUser }),
+ routeContext: { user: testUser },
+ },
+ },
+ }),
+ ).toThrow('has both "beforeLoad" and "routeContext"')
+ })
+})
+
+describe('createIsolatedTestRouter', () => {
+ test('renders one element in one route with the state the test supplies', async () => {
+ const app = createApp()
+
+ const router = await createIsolatedTestRouter({
+ routeTree: app.routeTree,
+ route: '/_authed/posts/$postId',
+ element: ,
+ params: { postId: '5' },
+ search: { tab: 'comments' },
+ context: seededContext,
+ loaderData: {
+ '/_authed': { unreadCount: 4 },
+ '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } },
+ },
+ })
+ render()
+
+ // The router has loaded, so the first render is complete.
+ expect(screen.getByRole('heading')).toHaveTextContent('Seeded post')
+ expect(
+ screen.getByText(
+ 'Test user reads post 5 in en on tab comments with 4 unread in seeded scope',
+ ),
+ ).toBeInTheDocument()
+ expect(router.state.location.pathname).toBe('/posts/5')
+
+ // Nothing of the application ran or rendered.
+ expect(app.calls).toEqual([])
+ expect(screen.queryByText('App shell')).not.toBeInTheDocument()
+ expect(screen.queryByText('Authed layout')).not.toBeInTheDocument()
+ expect(screen.queryByText('Post page')).not.toBeInTheDocument()
+ })
+
+ test('sends search params through validateSearch', async () => {
+ const app = createApp()
+ const state = {
+ routeTree: app.routeTree,
+ route: '/_authed/posts/$postId',
+ params: { postId: '5' },
+ context: seededContext,
+ loaderData: {
+ '/_authed': { unreadCount: 4 },
+ '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } },
+ },
+ } as const
+
+ const router = await createIsolatedTestRouter({
+ ...state,
+ element: ,
+ })
+ render()
+ expect(screen.getByText(/on tab details/)).toBeInTheDocument()
+
+ await expect(
+ createIsolatedTestRouter({
+ ...state,
+ element: ,
+ search: { tab: 'broken' },
+ }),
+ ).rejects.toThrow('Unknown tab')
+ })
+
+ test('navigates with the real router and renders no other route', async () => {
+ const app = createApp()
+
+ const router = await createIsolatedTestRouter({
+ routeTree: app.routeTree,
+ route: '/_authed/posts/$postId',
+ element: ,
+ params: { postId: '5' },
+ context: seededContext,
+ loaderData: {
+ '/_authed': { unreadCount: 4 },
+ '/_authed/posts/$postId': { post: { id: '5', title: 'Seeded post' } },
+ },
+ })
+ render()
+
+ fireEvent.click(screen.getByRole('link', { name: 'Sign out' }))
+
+ await waitFor(() => {
+ expect(router.state.location.pathname).toBe('/login')
+ })
+ expect(screen.queryByText('Login page')).not.toBeInTheDocument()
+ expect(app.calls).toEqual([])
+ })
+
+ test('does not load lazy routes', async () => {
+ const app = createApp()
+
+ const router = await createIsolatedTestRouter({
+ routeTree: app.routeTree,
+ route: '/lazy',
+ element: In the lazy route
,
+ context: { locale: 'en', session: { user: null } },
+ })
+ render()
+
+ expect(screen.getByText('In the lazy route')).toBeInTheDocument()
+ expect(app.loadLazyRoute).not.toHaveBeenCalled()
+ })
+
+ test('passes the other options to the router, except the default components', async () => {
+ const app = createApp()
+
+ const router = await createIsolatedTestRouter({
+ routeTree: app.routeTree,
+ route: '/login',
+ element: Element
,
+ context: { locale: 'en', session: { user: null } },
+ Wrap: ({ children }) => (
+
+ ),
+ defaultComponent: () => Default component
,
+ })
+ render()
+
+ expect(screen.getByLabelText('Providers')).toHaveTextContent('Element')
+ expect(screen.queryByText('Default component')).not.toBeInTheDocument()
+ })
+
+ test('renders no not-found component of the app after a navigation', async () => {
+ const app = createApp()
+ // The router warns that no not-found component is configured.
+ const consoleWarn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+
+ const router = await createIsolatedTestRouter({
+ routeTree: app.routeTree,
+ route: '/login',
+ element: Element
,
+ context: { locale: 'en', session: { user: null } },
+ defaultNotFoundComponent: () => App not found
,
+ })
+ render()
+
+ router.history.push('/missing')
+
+ expect(await screen.findByText('Not Found')).toBeInTheDocument()
+ expect(screen.queryByText('App not found')).not.toBeInTheDocument()
+ consoleWarn.mockRestore()
+ })
+
+ test('lets an error of the element reach the test', async () => {
+ const app = createApp()
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
+ function Broken(): never {
+ throw new Error('The element is broken')
+ }
+
+ const router = await createIsolatedTestRouter({
+ routeTree: app.routeTree,
+ route: '/login',
+ element: ,
+ context: { locale: 'en', session: { user: null } },
+ })
+
+ expect(() => render()).toThrow(
+ 'The element is broken',
+ )
+ consoleError.mockRestore()
+ })
+
+ test('fails when a path param is missing', async () => {
+ const app = createApp()
+
+ await expect(
+ createIsolatedTestRouter({
+ routeTree: app.routeTree,
+ route: '/_authed/posts/$postId',
+ element: ,
+ // @ts-expect-error `postId` is missing
+ params: {},
+ context: seededContext,
+ loaderData: {
+ '/_authed': { unreadCount: 4 },
+ '/_authed/posts/$postId': {
+ post: { id: '5', title: 'Seeded post' },
+ },
+ },
+ }),
+ ).rejects.toThrow(
+ 'Missing path params for route "/_authed/posts/$postId": postId.',
+ )
+ })
+
+ test('fails when the path of the route does not lead to it', async () => {
+ const app = createApp()
+
+ await expect(
+ createIsolatedTestRouter({
+ routeTree: app.routeTree,
+ route: '/_authed',
+ element: Element
,
+ context: { locale: 'en', session: { user: testUser }, user: testUser },
+ loaderData: { '/_authed': { unreadCount: 4 } },
+ }),
+ ).rejects.toThrow('The route "/_authed" is not matched at "/"')
+ })
+
+ test('fails for a route that does not exist', async () => {
+ const app = createApp()
+
+ await expect(
+ createIsolatedTestRouter({
+ routeTree: app.routeTree,
+ // @ts-expect-error not a route id of this tree
+ route: '/missing',
+ element: Element
,
+ }),
+ ).rejects.toThrow('The route "/missing" does not exist in the route tree')
+ })
+})
diff --git a/packages/react-router/vite.config.ts b/packages/react-router/vite.config.ts
index 798d9b74e4..7d82212668 100644
--- a/packages/react-router/vite.config.ts
+++ b/packages/react-router/vite.config.ts
@@ -32,6 +32,7 @@ export default mergeConfig(
'./src/index.dev.tsx',
'./src/ssr/client.ts',
'./src/ssr/server.ts',
+ './src/testing.ts',
],
srcDir: './src',
}),
diff --git a/packages/router-core/package.json b/packages/router-core/package.json
index ed2b794278..122457db0a 100644
--- a/packages/router-core/package.json
+++ b/packages/router-core/package.json
@@ -68,6 +68,16 @@
"default": "./dist/cjs/ssr/client.cjs"
}
},
+ "./testing": {
+ "import": {
+ "types": "./dist/esm/testing/index.d.ts",
+ "default": "./dist/esm/testing/index.js"
+ },
+ "require": {
+ "types": "./dist/cjs/testing/index.d.cts",
+ "default": "./dist/cjs/testing/index.cjs"
+ }
+ },
"./isServer": {
"development": {
"import": {
diff --git a/packages/router-core/src/testing/index.ts b/packages/router-core/src/testing/index.ts
new file mode 100644
index 0000000000..00d944b254
--- /dev/null
+++ b/packages/router-core/src/testing/index.ts
@@ -0,0 +1,30 @@
+export { createIsolatedTestRouterWith, createTestRouterWith } from './router'
+export type {
+ AnyIsolatedTestRouterOptions,
+ AnyTestRouterOptions,
+ TestRouterFactory,
+} from './router'
+export {
+ assertIsolatedRouteLoaded,
+ assertRouteTestParams,
+ createIsolatedRouteTree,
+ createTestRouteTree,
+ initRouteTree,
+ setTestRouterLocation,
+} from './routeTree'
+export type {
+ AnyRouteTestOverride,
+ AnyRouteTestOverrides,
+ IsolatedRouteTreeOptions,
+} from './routeTree'
+export type {
+ IsolatedRouteState,
+ IsolatedTestRouterOptions,
+ RouteTestBeforeLoadFn,
+ RouteTestComponents,
+ RouteTestContextFn,
+ RouteTestLoaderFn,
+ RouteTestOverride,
+ RouteTestOverrides,
+ TestRouterOptions,
+} from './types'
diff --git a/packages/router-core/src/testing/routeTree.ts b/packages/router-core/src/testing/routeTree.ts
new file mode 100644
index 0000000000..0f4de1092d
--- /dev/null
+++ b/packages/router-core/src/testing/routeTree.ts
@@ -0,0 +1,344 @@
+import { SEGMENT_TYPE_PARAM } from '../new-process-route-tree'
+import { isNotFound } from '../not-found'
+import type { AnyRoute } from '../route'
+import type { AnyRouter } from '../router'
+
+type RouteOptionsPatch = Record
+
+/**
+ * The untyped shape of a per-route override. The typed shape that tests use
+ * is `RouteTestOverride` in `./types`.
+ */
+export interface AnyRouteTestOverride {
+ beforeLoad?: unknown
+ loader?: unknown
+ context?: unknown
+ loaderData?: unknown
+ routeContext?: unknown
+ component?: unknown
+ pendingComponent?: unknown
+ errorComponent?: unknown
+ notFoundComponent?: unknown
+}
+
+export type AnyRouteTestOverrides = Record<
+ string,
+ AnyRouteTestOverride | undefined
+>
+
+/** Override keys that replace the route option of the same name. */
+const replacedOptions = [
+ 'beforeLoad',
+ 'loader',
+ 'context',
+ 'component',
+ 'pendingComponent',
+ 'errorComponent',
+ 'notFoundComponent',
+] as const
+
+/**
+ * Everything an isolated route test removes from every route: the options
+ * that do work, the options that render, and the options that react to the
+ * lifecycle. The options derived from the URL (`params`, `validateSearch`,
+ * `search`, `loaderDeps`) stay.
+ */
+const isolatedRouteOptions: RouteOptionsPatch = {
+ beforeLoad: undefined,
+ context: undefined,
+ loader: undefined,
+ component: undefined,
+ pendingComponent: undefined,
+ errorComponent: undefined,
+ notFoundComponent: undefined,
+ shellComponent: undefined,
+ head: undefined,
+ scripts: undefined,
+ headers: undefined,
+ onEnter: undefined,
+ onStay: undefined,
+ onLeave: undefined,
+ onError: undefined,
+ onCatch: undefined,
+}
+
+function getChildren(route: AnyRoute): Array | undefined {
+ return route.children as Array | undefined
+}
+
+/**
+ * Gives every route of a tree its `id`, `path`, `fullPath` and `to`.
+ *
+ * A router does this for the tree it is built from, every time one is
+ * created. A test router is built from a copy of the tree, so without this
+ * step the route objects that application code imports would never be
+ * initialised: `Route.to` would be `undefined` and `Route.useLoaderData()`
+ * would fall back to the nearest match.
+ */
+export function initRouteTree(routeTree: AnyRoute): void {
+ let index = 0
+ const visit = (route: AnyRoute) => {
+ route.init(index++)
+ getChildren(route)?.forEach(visit)
+ }
+ visit(routeTree)
+}
+
+function cloneRouteTree(
+ routeTree: TRouteTree,
+ getPatch: (route: AnyRoute) => RouteOptionsPatch | undefined,
+ keepLazyRoutes: boolean,
+): TRouteTree {
+ const cloneRoute = (route: AnyRoute, parent?: AnyRoute): AnyRoute => {
+ const patch = getPatch(route)
+ // Route classes take all their state from `options`, so a fresh instance
+ // of the same class with copied options is an independent route.
+ const clone = new (route.constructor as new () => AnyRoute)()
+ clone.options = { ...route.options, ...patch }
+ if (parent) {
+ clone.options.getParentRoute = () => parent
+ }
+ clone.isRoot = route.isRoot
+
+ const lazyFn = route.lazyFn
+ if (lazyFn && keepLazyRoutes) {
+ // Lazy options are assigned onto the route when they arrive. The test's
+ // own options have to win over them.
+ clone.lazyFn = patch
+ ? () =>
+ lazyFn().then(
+ (lazyRoute) =>
+ ({
+ options: { ...lazyRoute.options, ...patch },
+ }) as typeof lazyRoute,
+ )
+ : lazyFn
+ }
+
+ const children = getChildren(route)
+ if (children) {
+ clone.addChildren(children.map((child) => cloneRoute(child, clone)))
+ }
+ return clone
+ }
+
+ return cloneRoute(routeTree) as TRouteTree
+}
+
+function collectRouteIds(routeTree: AnyRoute, ids = new Set()) {
+ ids.add(routeTree.id)
+ getChildren(routeTree)?.forEach((child) => collectRouteIds(child, ids))
+ return ids
+}
+
+function assertKnownRouteIds(routeTree: AnyRoute, ids: Iterable) {
+ let known: Set | undefined
+ for (const id of ids) {
+ known ??= collectRouteIds(routeTree)
+ if (!known.has(id)) {
+ throw new Error(
+ `The route "${id}" does not exist in the route tree. Known route ids: ${[...known].join(', ')}`,
+ )
+ }
+ }
+}
+
+function applyOverride(
+ routeId: string,
+ override: AnyRouteTestOverride,
+): RouteOptionsPatch {
+ const conflict =
+ 'loader' in override && 'loaderData' in override
+ ? ['loader', 'loaderData']
+ : 'routeContext' in override && 'context' in override
+ ? ['context', 'routeContext']
+ : 'routeContext' in override && 'beforeLoad' in override
+ ? ['beforeLoad', 'routeContext']
+ : undefined
+ if (conflict) {
+ throw new Error(
+ `The override for route "${routeId}" has both "${conflict[0]}" and "${conflict[1]}". Pass one of them.`,
+ )
+ }
+ if (
+ override.context !== undefined &&
+ typeof override.context !== 'function'
+ ) {
+ throw new Error(
+ `The override for route "${routeId}" passes a value as "context", which replaces the route's \`context\` option and has to be a function. To seed what the route adds to the context, use "routeContext".`,
+ )
+ }
+
+ const patch: RouteOptionsPatch = {}
+ for (const key of replacedOptions) {
+ if (key in override) {
+ patch[key] = override[key]
+ }
+ }
+ if ('loaderData' in override) {
+ const loaderData = override.loaderData
+ patch.loader = () => loaderData
+ }
+ if ('routeContext' in override) {
+ // The seed stands for everything the route adds to the context, so
+ // neither of the two options that produce it may run.
+ const routeContext = override.routeContext
+ patch.context = () => routeContext
+ patch.beforeLoad = undefined
+ }
+ return patch
+}
+
+/**
+ * Copies a route tree for one test router and applies per-route overrides.
+ * Routes without an override keep the application's options.
+ */
+export function createTestRouteTree(
+ routeTree: TRouteTree,
+ overrides?: AnyRouteTestOverrides,
+): TRouteTree {
+ initRouteTree(routeTree)
+ if (overrides) {
+ assertKnownRouteIds(routeTree, Object.keys(overrides))
+ }
+
+ return cloneRouteTree(
+ routeTree,
+ (route) => {
+ const override = overrides?.[route.id]
+ return override ? applyOverride(route.id, override) : undefined
+ },
+ true,
+ )
+}
+
+export interface IsolatedRouteTreeOptions {
+ /** The route the element under test is rendered in. */
+ routeId: string
+ /** The component that renders the element under test. */
+ component: unknown
+ /** Loader data by route id. A route that is not listed has no loader. */
+ loaderData: ReadonlyMap
+}
+
+/**
+ * Copies a route tree for an isolated route test. No route keeps an option
+ * that does work or renders. The target route renders `component`, and the
+ * listed routes get a loader that returns the given data.
+ */
+export function createIsolatedRouteTree(
+ routeTree: TRouteTree,
+ options: IsolatedRouteTreeOptions,
+): TRouteTree {
+ initRouteTree(routeTree)
+ assertKnownRouteIds(routeTree, [
+ options.routeId,
+ ...options.loaderData.keys(),
+ ])
+
+ return cloneRouteTree(
+ routeTree,
+ (route) => {
+ const patch = { ...isolatedRouteOptions }
+ if (options.loaderData.has(route.id)) {
+ const loaderData = options.loaderData.get(route.id)
+ patch.loader = () => loaderData
+ }
+ if (route.id === options.routeId) {
+ patch.component = options.component
+ }
+ return patch
+ },
+ false,
+ )
+}
+
+/**
+ * Moves a router that has not loaded yet to a location given as navigation
+ * options (`to`, `params`, `search`, `hash`, `state`).
+ */
+export function setTestRouterLocation(
+ router: AnyRouter,
+ location: object,
+): void {
+ const next = router.buildLocation(location as never)
+ router.history.replace(next.publicHref, next.state)
+ router.updateLatestLocation()
+}
+
+/**
+ * Throws when navigation options for `routeId` leave a required path param
+ * out. Without this the param would be written into the URL as "undefined".
+ */
+export function assertRouteTestParams(
+ router: AnyRouter,
+ routeId: string,
+ params: Record | undefined,
+): void {
+ const route = (router.routesById as Record)[routeId]!
+ const missing: Array = []
+ for (const segment of route._interpolation ?? []) {
+ if (
+ typeof segment !== 'string' &&
+ segment[0] === SEGMENT_TYPE_PARAM &&
+ params?.[segment[1]] == null
+ ) {
+ missing.push(segment[1])
+ }
+ }
+ if (missing.length) {
+ throw new Error(
+ `Missing path params for route "${routeId}": ${missing.join(', ')}.`,
+ )
+ }
+}
+
+/**
+ * Throws when an isolated route test did not end up where the test asked: a
+ * route threw `notFound()` or failed to load, for example because the search
+ * params did not pass its `validateSearch`, or the target route is not
+ * matched.
+ */
+export function assertIsolatedRouteLoaded(
+ router: AnyRouter,
+ routeId: string,
+): void {
+ const matches = router.state.matches
+ const href = router.state.location.href
+
+ for (const match of matches) {
+ if (match.status === 'notFound') {
+ const step = isNotFound(match.paramsError)
+ ? ' while parsing its path params'
+ : ''
+ throw new Error(
+ `The route "${match.routeId}" threw notFound()${step} at "${href}".`,
+ { cause: match.error },
+ )
+ }
+ if (match.status === 'error') {
+ // A `notFound()` from `validateSearch` arrives wrapped in a
+ // `SearchParamError` without a message, and the match fails.
+ if (isNotFound((match.searchError as Error | undefined)?.cause)) {
+ throw new Error(
+ `The route "${match.routeId}" threw notFound() while validating its search params at "${href}".`,
+ { cause: match.error },
+ )
+ }
+ throw match.error instanceof Error
+ ? match.error
+ : new Error(
+ `The route "${match.routeId}" failed to load at "${href}": ${String(match.error)}`,
+ )
+ }
+ }
+
+ const matched = matches.some(
+ (match) => match.routeId === routeId && match.status === 'success',
+ )
+ if (!matched) {
+ throw new Error(
+ `The route "${routeId}" is not matched at "${href}". Matched routes: ${matches.map((match) => match.routeId).join(', ') || 'none'}. Pass the id of a route that its own path leads to; a layout route is reached through one of its child routes.`,
+ )
+ }
+}
diff --git a/packages/router-core/src/testing/router.ts b/packages/router-core/src/testing/router.ts
new file mode 100644
index 0000000000..f416914c0e
--- /dev/null
+++ b/packages/router-core/src/testing/router.ts
@@ -0,0 +1,129 @@
+import { createMemoryHistory } from '@tanstack/history'
+import {
+ assertIsolatedRouteLoaded,
+ assertRouteTestParams,
+ createIsolatedRouteTree,
+ createTestRouteTree,
+ setTestRouterLocation,
+} from './routeTree'
+import type { RouterHistory } from '@tanstack/history'
+import type { AnyRoute } from '../route'
+import type { AnyRouter } from '../router'
+import type { AnyRouteTestOverrides } from './routeTree'
+
+/** A framework's `createRouter`. */
+export type TestRouterFactory = (
+ options: any,
+) => TRouter
+
+/** The untyped options of `createTestRouterWith`. */
+export interface AnyTestRouterOptions {
+ routeTree: AnyRoute
+ location?: object
+ overrides?: AnyRouteTestOverrides
+ history?: RouterHistory
+ [option: string]: unknown
+}
+
+/** The untyped options of `createIsolatedTestRouterWith`. */
+export interface AnyIsolatedTestRouterOptions {
+ routeTree: AnyRoute
+ /** The framework component that renders the element under test. */
+ component: unknown
+ route: string
+ params?: Record
+ search?: Record
+ context?: Record
+ loaderData?: Record
+ [option: string]: unknown
+}
+
+function assertNoNotFoundRoute(notFoundRoute: unknown): void {
+ if (notFoundRoute !== undefined) {
+ throw new Error(
+ 'Test routers do not support the deprecated "notFoundRoute" option. Give the root route a "notFoundComponent" instead.',
+ )
+ }
+}
+
+/**
+ * The framework-independent part of `createTestRouter`. Framework packages
+ * call it with their own `createRouter` and declare the typed signature.
+ *
+ * Creates a router over a copy of the route tree with the overrides applied.
+ * The router uses a memory history unless `history` is given, and starts at
+ * `location`. It has not loaded yet.
+ */
+export function createTestRouterWith(
+ createRouter: TestRouterFactory,
+ options: AnyTestRouterOptions,
+): TRouter {
+ assertNoNotFoundRoute(options.notFoundRoute)
+ const { routeTree, location, overrides, history, ...routerOptions } = options
+ const router = createRouter({
+ ...routerOptions,
+ routeTree: createTestRouteTree(routeTree, overrides),
+ history: history ?? createMemoryHistory(),
+ })
+
+ if (location) {
+ setTestRouterLocation(router, location)
+ }
+
+ return router
+}
+
+/**
+ * The framework-independent part of `createIsolatedTestRouter`. Framework
+ * packages call it with their own `createRouter`, turn the element under test
+ * into `component`, and declare the typed signature.
+ *
+ * Creates a router in which no route option that does work or renders
+ * remains, renders `component` in the route `route`, and resolves once the
+ * router has loaded at that route's location.
+ */
+export async function createIsolatedTestRouterWith(
+ createRouter: TestRouterFactory,
+ options: AnyIsolatedTestRouterOptions,
+): Promise {
+ assertNoNotFoundRoute(options.notFoundRoute)
+ const {
+ routeTree,
+ component,
+ route,
+ params,
+ search,
+ context,
+ loaderData,
+ ...routerOptions
+ } = options
+
+ const router = createRouter({
+ ...routerOptions,
+ // Nothing of the application renders around the element, and the router
+ // does not catch an error that the element throws.
+ defaultComponent: undefined,
+ defaultErrorComponent: undefined,
+ defaultPendingComponent: undefined,
+ defaultNotFoundComponent: undefined,
+ disableGlobalCatchBoundary: true,
+ routeTree: createIsolatedRouteTree(routeTree, {
+ routeId: route,
+ component,
+ loaderData: new Map(Object.entries(loaderData ?? {})),
+ }),
+ history: createMemoryHistory(),
+ context,
+ })
+
+ assertRouteTestParams(router, route, params)
+ setTestRouterLocation(router, {
+ to: (router.routesById as Record)[route]!.fullPath,
+ params,
+ search,
+ })
+ await router.load()
+ assertIsolatedRouteLoaded(router, route)
+
+ return router
+}
diff --git a/packages/router-core/src/testing/types.ts b/packages/router-core/src/testing/types.ts
new file mode 100644
index 0000000000..72711605c2
--- /dev/null
+++ b/packages/router-core/src/testing/types.ts
@@ -0,0 +1,271 @@
+import type { RouterHistory } from '@tanstack/history'
+import type {
+ AnyRoute,
+ BeforeLoadContextOptions,
+ ContextAsyncReturnType,
+ ContextReturnType,
+ LoaderFnContext,
+ RouteContextOptions,
+} from '../route'
+import type { RouteById, RouteIds } from '../routeInfo'
+import type {
+ RouterConstructorOptions,
+ RouterCore,
+ RouterOptions,
+ TrailingSlashOption,
+} from '../router'
+import type { ValidateNavigateOptions } from '../typePrimitives'
+import type { Awaitable, ConstrainLiteral } from '../utils'
+
+/**
+ * The component options a test can replace on a route. Framework packages
+ * pass their own component types.
+ */
+export interface RouteTestComponents {
+ component?: unknown
+ pendingComponent?: unknown
+ errorComponent?: unknown
+ notFoundComponent?: unknown
+}
+
+/** `true` when a value of this type holds nothing a test has to supply. */
+type IsEmpty = [TValue] extends [void | undefined | null]
+ ? true
+ : {} extends TValue
+ ? true
+ : false
+
+type OrVoid = IsEmpty extends true ? TValue | void : TValue
+
+type OptionalWhenEmpty =
+ IsEmpty extends true
+ ? { [K in TKey]?: TValue }
+ : { [K in TKey]: TValue }
+
+/**
+ * A replacement for a route's `beforeLoad`. It receives what the route's own
+ * `beforeLoad` receives and has to return what that one returns.
+ */
+export type RouteTestBeforeLoadFn = (
+ ctx: BeforeLoadContextOptions<
+ any,
+ TRoute['types']['parentRoute'],
+ TRoute['types']['searchValidator'],
+ TRoute['types']['params'],
+ TRoute['types']['routerContext'],
+ TRoute['types']['routeContextFn'],
+ TRoute['types']['id'],
+ any,
+ any
+ >,
+) => Awaitable>>
+
+/**
+ * A replacement for a route's `loader`. It receives what the route's own
+ * loader receives and has to return the route's loader data.
+ */
+export type RouteTestLoaderFn = (
+ ctx: LoaderFnContext<
+ any,
+ TRoute['types']['parentRoute'],
+ TRoute['types']['id'],
+ TRoute['types']['params'],
+ TRoute['types']['loaderDeps'],
+ TRoute['types']['routerContext'],
+ TRoute['types']['routeContextFn'],
+ TRoute['types']['beforeLoadFn'],
+ any,
+ any
+ >,
+) => Awaitable<
+ | TRoute['types']['loaderData']
+ | (undefined extends TRoute['types']['loaderData'] ? void : never)
+>
+
+/** A replacement for a route's `context` option. */
+export type RouteTestContextFn = (
+ ctx: RouteContextOptions<
+ TRoute['types']['parentRoute'],
+ TRoute['types']['params'],
+ TRoute['types']['routerContext'],
+ TRoute['types']['loaderDeps'],
+ TRoute['types']['id']
+ >,
+) => OrVoid>
+
+/**
+ * What a test can replace on one route. Everything is typed from the route.
+ *
+ * - `beforeLoad`, `loader`, `context`: replace the route option of the same
+ * name. Each takes a function with the signature of the original.
+ * - `loaderData`: a seed for the route's loader data. The route's loader does
+ * not run.
+ * - `routeContext`: a seed for everything the route adds to the context.
+ * Neither the route's `context` option nor its `beforeLoad` runs.
+ * - The component options replace what the route renders.
+ *
+ * The options derived from the URL (`params`, `validateSearch`, `loaderDeps`)
+ * cannot be replaced.
+ */
+export type RouteTestOverride<
+ TRoute extends AnyRoute,
+ TComponents = RouteTestComponents,
+> = TComponents & {
+ beforeLoad?: RouteTestBeforeLoadFn
+ loader?: RouteTestLoaderFn
+ context?: RouteTestContextFn
+ loaderData?: TRoute['types']['loaderData']
+ routeContext?: TRoute['types']['routeContext']
+}
+
+/**
+ * Overrides by route id. The root route's id is `rootRouteId`, used as a
+ * computed key: `{ [rootRouteId]: { ... } }`.
+ */
+export type RouteTestOverrides<
+ TRouteTree extends AnyRoute,
+ TComponents = RouteTestComponents,
+> = {
+ [TId in RouteIds]?: RouteTestOverride<
+ RouteById,
+ TComponents
+ >
+}
+
+type AncestorRoutes = TRoute extends {
+ types: { parentRoute: infer TParentRoute }
+}
+ ? // The parent of a root route is `any`.
+ unknown extends TParentRoute
+ ? never
+ : TParentRoute extends AnyRoute
+ ? TParentRoute | AncestorRoutes
+ : never
+ : never
+
+type BranchRoutes = TRoute | AncestorRoutes
+
+type HasLoaderData =
+ undefined extends TRoute['types']['loaderData'] ? false : true
+
+/**
+ * Loader data by route id for a route and the routes above it. A route whose
+ * loader returns data needs an entry.
+ */
+type BranchLoaderData = {
+ [TBranchRoute in BranchRoutes as HasLoaderData extends true
+ ? TBranchRoute['types']['id']
+ : never]: TBranchRoute['types']['loaderData']
+} & {
+ [TBranchRoute in BranchRoutes as HasLoaderData extends true
+ ? never
+ : TBranchRoute['types']['id']]?: TBranchRoute['types']['loaderData']
+}
+
+type IsolatedRouteStateFor = OptionalWhenEmpty<
+ 'params',
+ TRoute['types']['allParams']
+> &
+ OptionalWhenEmpty<'search', TRoute['types']['fullSearchSchemaInput']> &
+ OptionalWhenEmpty<'context', TRoute['types']['allContext']> &
+ OptionalWhenEmpty<'loaderData', BranchLoaderData>
+
+/**
+ * The state an isolated route test supplies for the route `TId`. No route
+ * option that does work runs in such a test, so the types ask for what those
+ * options would have produced:
+ *
+ * - `params`: all path params of the route.
+ * - `search`: search params, which still go through `validateSearch`.
+ * - `context`: the whole context of the route.
+ * - `loaderData`: loader data by route id, for the route and the routes above
+ * it whose loader returns data.
+ */
+export type IsolatedRouteState<
+ TRouteTree extends AnyRoute,
+ TId extends RouteIds,
+> = {
+ route: TId
+} & IsolatedRouteStateFor>
+
+/**
+ * The options of `createTestRouter`: those of `createRouter`, plus the route
+ * tree, a start location and per-route overrides. Framework packages pass
+ * their component types as `TComponents`.
+ */
+export type TestRouterOptions<
+ TRouteTree extends AnyRoute,
+ TLocation = unknown,
+ TTrailingSlashOption extends TrailingSlashOption = 'never',
+ TDefaultStructuralSharingOption extends boolean = false,
+ TRouterHistory extends RouterHistory = RouterHistory,
+ TDehydrated extends Record = Record,
+ TComponents = RouteTestComponents,
+> = RouterConstructorOptions<
+ TRouteTree,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ TRouterHistory,
+ TDehydrated
+> & {
+ routeTree: TRouteTree
+ /**
+ * Where the router starts, typed like the options of `navigate`. It
+ * replaces the current entry of `history`. Without it, the router starts
+ * at the current location of `history`: `/` for the default memory history.
+ */
+ location?: ValidateNavigateOptions<
+ RouterCore<
+ TRouteTree,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ TRouterHistory,
+ TDehydrated
+ >,
+ TLocation
+ >
+ /**
+ * Per-route overrides. A route that is not listed keeps the application's
+ * options.
+ */
+ overrides?: RouteTestOverrides
+ /**
+ * Not supported: the option is deprecated. Give the root route a
+ * `notFoundComponent` instead.
+ */
+ notFoundRoute?: never
+}
+
+/**
+ * The options of `createIsolatedTestRouter`. Framework packages pass the type
+ * of the element under test as `TElement`.
+ */
+export type IsolatedTestRouterOptions<
+ TRouteTree extends AnyRoute,
+ TId,
+ TElement,
+ TTrailingSlashOption extends TrailingSlashOption = 'never',
+ TDefaultStructuralSharingOption extends boolean = false,
+> = Omit<
+ RouterOptions<
+ TRouteTree,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ RouterHistory,
+ Record
+ >,
+ // `search` is the route's search params here, not the router option.
+ 'routeTree' | 'history' | 'context' | 'search'
+> & {
+ routeTree: TRouteTree
+ /** The element under test. It renders in place of the route's component. */
+ element: TElement
+ /**
+ * Not supported: the option is deprecated. Give the root route a
+ * `notFoundComponent` instead.
+ */
+ notFoundRoute?: never
+ // Checked here rather than in a constraint on `TId`: with a constraint,
+ // TypeScript widens a constant such as `rootRouteId` while inferring.
+ route: ConstrainLiteral>
+} & IsolatedRouteStateFor>
diff --git a/packages/router-core/tests/testing.test.ts b/packages/router-core/tests/testing.test.ts
new file mode 100644
index 0000000000..6b052a6bc3
--- /dev/null
+++ b/packages/router-core/tests/testing.test.ts
@@ -0,0 +1,614 @@
+import { describe, expect, test, vi } from 'vitest'
+import { createMemoryHistory } from '@tanstack/history'
+import { BaseRootRoute, BaseRoute, notFound } from '../src'
+import {
+ assertIsolatedRouteLoaded,
+ assertRouteTestParams,
+ createIsolatedRouteTree,
+ createIsolatedTestRouterWith,
+ createTestRouteTree,
+ createTestRouterWith,
+ initRouteTree,
+ setTestRouterLocation,
+} from '../src/testing'
+import { createTestRouter } from './routerTestUtils'
+import type { AnyRoute } from '../src'
+
+function createTree() {
+ const calls: Array = []
+ const loadLazyRoute = vi.fn(() =>
+ Promise.resolve({ options: { component: 'lazy component' } } as any),
+ )
+
+ const rootRoute = new BaseRootRoute({
+ beforeLoad: () => {
+ calls.push('root.beforeLoad')
+ return { session: 'real session' }
+ },
+ component: 'root component',
+ shellComponent: 'root shell',
+ })
+
+ const layoutRoute = new BaseRoute({
+ getParentRoute: () => rootRoute,
+ id: 'layout',
+ loader: () => {
+ calls.push('layout.loader')
+ return 'real layout data'
+ },
+ component: 'layout component',
+ })
+
+ const postRoute = new BaseRoute({
+ getParentRoute: () => layoutRoute,
+ path: '/posts/$postId',
+ params: {
+ parse: (params: { postId: string }) => {
+ if (params.postId === 'missing') {
+ throw notFound()
+ }
+ return params
+ },
+ },
+ validateSearch: (search: Record) => {
+ if (search.tab === 'broken') {
+ throw new Error('Unknown tab')
+ }
+ if (search.tab === 'missing') {
+ throw notFound()
+ }
+ return { tab: (search.tab as string | undefined) ?? 'details' }
+ },
+ context: () => {
+ calls.push('post.context')
+ return { scope: 'real scope' }
+ },
+ beforeLoad: () => {
+ calls.push('post.beforeLoad')
+ return { permission: 'real permission' }
+ },
+ loader: () => {
+ calls.push('post.loader')
+ return 'real post data'
+ },
+ onEnter: () => {
+ calls.push('post.onEnter')
+ },
+ component: 'post component',
+ errorComponent: 'post error component',
+ })
+
+ const lazyRoute = new BaseRoute({
+ getParentRoute: () => rootRoute,
+ path: '/lazy',
+ }).lazy(loadLazyRoute)
+
+ const indexRoute = new BaseRoute({
+ getParentRoute: () => rootRoute,
+ path: '/',
+ })
+
+ const routeTree = rootRoute.addChildren([
+ layoutRoute.addChildren([postRoute]),
+ lazyRoute,
+ indexRoute,
+ ])
+
+ return { routeTree, rootRoute, layoutRoute, postRoute, calls, loadLazyRoute }
+}
+
+function createRouter(routeTree: AnyRoute, href: string) {
+ return createTestRouter({
+ routeTree,
+ history: createMemoryHistory({ initialEntries: [href] }),
+ context: { locale: 'en' },
+ })
+}
+
+function getMatch(router: ReturnType, routeId: string) {
+ return router.state.matches.find((match) => match.routeId === routeId)
+}
+
+describe('initRouteTree', () => {
+ test('gives every route its id and paths without a router', () => {
+ const { routeTree, layoutRoute, postRoute } = createTree()
+ expect(postRoute.id).toBeUndefined()
+
+ initRouteTree(routeTree)
+
+ expect(routeTree.id).toBe('__root__')
+ expect(layoutRoute.id).toBe('/layout')
+ expect(postRoute.id).toBe('/layout/posts/$postId')
+ expect(postRoute.fullPath).toBe('/posts/$postId')
+ expect(postRoute.to).toBe('/posts/$postId')
+ expect(postRoute.parentRoute).toBe(layoutRoute)
+ })
+
+ test('initialises routes added to a tree that a router has processed', () => {
+ const { routeTree, rootRoute } = createTree()
+ createRouter(routeTree, '/')
+ const aboutRoute = new BaseRoute({
+ getParentRoute: () => rootRoute,
+ path: '/about',
+ })
+ rootRoute.addChildren([
+ ...(rootRoute.children as Array),
+ aboutRoute,
+ ])
+
+ expect(() =>
+ createTestRouteTree(routeTree, {
+ '/about': { loaderData: 'seeded about data' },
+ }),
+ ).not.toThrow()
+ expect(aboutRoute.id).toBe('/about')
+ expect(aboutRoute.to).toBe('/about')
+ })
+})
+
+describe('createTestRouteTree', () => {
+ test('copies every route and leaves the original tree untouched', async () => {
+ const { routeTree, postRoute, calls } = createTree()
+ const originalOptions = { ...postRoute.options }
+
+ const testTree = createTestRouteTree(routeTree, {
+ '/layout/posts/$postId': { loaderData: 'seeded post data' },
+ })
+ const router = createRouter(testTree, '/posts/1')
+ await router.load()
+
+ const testPostRoute = router.routesById['/layout/posts/$postId']!
+ expect(testPostRoute).not.toBe(postRoute)
+ expect(testPostRoute).toBeInstanceOf(BaseRoute)
+ expect(testPostRoute.parentRoute).toBe(router.routesById['/layout'])
+ expect(testPostRoute.parentRoute).not.toBe(postRoute.parentRoute)
+ expect(router.routesById['__root__']).toBeInstanceOf(BaseRootRoute)
+ expect(postRoute.options).toEqual(originalOptions)
+ expect(getMatch(router, '/layout/posts/$postId')?.loaderData).toBe(
+ 'seeded post data',
+ )
+ expect(calls).not.toContain('post.loader')
+
+ // The route objects that application code holds are initialised too.
+ expect(postRoute.id).toBe('/layout/posts/$postId')
+ expect(postRoute.to).toBe('/posts/$postId')
+ })
+
+ test('runs the options of the application for routes without an override', async () => {
+ const { routeTree, calls } = createTree()
+
+ const router = createRouter(createTestRouteTree(routeTree), '/posts/1')
+ await router.load()
+
+ expect(calls).toEqual([
+ 'root.beforeLoad',
+ 'post.context',
+ 'post.beforeLoad',
+ 'layout.loader',
+ 'post.loader',
+ 'post.onEnter',
+ ])
+ expect(getMatch(router, '/layout/posts/$postId')?.context).toEqual({
+ locale: 'en',
+ session: 'real session',
+ scope: 'real scope',
+ permission: 'real permission',
+ })
+ })
+
+ test('takes routeContext as a seed for everything the route contributes', async () => {
+ const { routeTree, calls } = createTree()
+
+ const router = createRouter(
+ createTestRouteTree(routeTree, {
+ '/layout/posts/$postId': { routeContext: { scope: 'seeded scope' } },
+ }),
+ '/posts/1',
+ )
+ await router.load()
+
+ expect(calls).not.toContain('post.context')
+ expect(calls).not.toContain('post.beforeLoad')
+ expect(getMatch(router, '/layout/posts/$postId')?.context).toEqual({
+ locale: 'en',
+ session: 'real session',
+ scope: 'seeded scope',
+ })
+ })
+
+ test('replaces the context option, beforeLoad and the loader with functions', async () => {
+ const { routeTree, calls } = createTree()
+ const loader = vi.fn(({ params }: { params: { postId: string } }) => {
+ return `replaced data for ${params.postId}`
+ })
+
+ const router = createRouter(
+ createTestRouteTree(routeTree, {
+ '/layout/posts/$postId': {
+ context: () => ({ scope: 'replaced scope' }),
+ beforeLoad: () => ({ permission: 'replaced permission' }),
+ loader,
+ },
+ }),
+ '/posts/7',
+ )
+ await router.load()
+
+ const match = getMatch(router, '/layout/posts/$postId')
+ expect(match?.context).toEqual({
+ locale: 'en',
+ session: 'real session',
+ scope: 'replaced scope',
+ permission: 'replaced permission',
+ })
+ expect(match?.loaderData).toBe('replaced data for 7')
+ expect(calls).toEqual(['root.beforeLoad', 'layout.loader', 'post.onEnter'])
+ })
+
+ test('seeds loader data and replaces components', async () => {
+ const { routeTree, calls } = createTree()
+
+ const router = createRouter(
+ createTestRouteTree(routeTree, {
+ '/layout': { loaderData: 'seeded layout data' },
+ '/layout/posts/$postId': { component: 'test component' },
+ }),
+ '/posts/1',
+ )
+ await router.load()
+
+ expect(getMatch(router, '/layout')?.loaderData).toBe('seeded layout data')
+ expect(calls).not.toContain('layout.loader')
+ expect(router.routesById['/layout/posts/$postId']!.options.component).toBe(
+ 'test component',
+ )
+ })
+
+ test('lets an override win over the options of a lazy route', async () => {
+ const { routeTree, loadLazyRoute } = createTree()
+
+ const real = createRouter(createTestRouteTree(routeTree), '/lazy')
+ await real.load()
+ expect(real.routesById['/lazy']!.options.component).toBe('lazy component')
+
+ const overridden = createRouter(
+ createTestRouteTree(routeTree, {
+ '/lazy': { component: 'test component' },
+ }),
+ '/lazy',
+ )
+ await overridden.load()
+ expect(overridden.routesById['/lazy']!.options.component).toBe(
+ 'test component',
+ )
+ expect(loadLazyRoute).toHaveBeenCalledTimes(2)
+ })
+
+ test('rejects an unknown route id and conflicting overrides', () => {
+ const { routeTree } = createTree()
+
+ expect(() => createTestRouteTree(routeTree, { '/missing': {} })).toThrow(
+ 'The route "/missing" does not exist in the route tree. Known route ids: __root__, /layout, /layout/posts/$postId, /lazy, /',
+ )
+ expect(() =>
+ createTestRouteTree(routeTree, {
+ '/layout': { loader: () => 'a', loaderData: 'b' },
+ }),
+ ).toThrow(
+ 'The override for route "/layout" has both "loader" and "loaderData". Pass one of them.',
+ )
+ expect(() =>
+ createTestRouteTree(routeTree, {
+ '/layout': { beforeLoad: () => ({}), routeContext: {} },
+ }),
+ ).toThrow(
+ 'The override for route "/layout" has both "beforeLoad" and "routeContext". Pass one of them.',
+ )
+ expect(() =>
+ createTestRouteTree(routeTree, {
+ '/layout': { context: () => ({}), routeContext: {} },
+ }),
+ ).toThrow(
+ 'The override for route "/layout" has both "context" and "routeContext". Pass one of them.',
+ )
+ })
+
+ test('rejects a value for the context option', () => {
+ const { routeTree } = createTree()
+
+ expect(() =>
+ createTestRouteTree(routeTree, {
+ '/layout': { context: { scope: 'a value' } },
+ }),
+ ).toThrow(
+ 'The override for route "/layout" passes a value as "context", which replaces the route\'s `context` option and has to be a function. To seed what the route adds to the context, use "routeContext".',
+ )
+ })
+})
+
+describe('createIsolatedRouteTree', () => {
+ test('keeps no option that does work or renders, and seeds the given loader data', async () => {
+ const { routeTree, calls, loadLazyRoute } = createTree()
+
+ const router = createRouter(
+ createIsolatedRouteTree(routeTree, {
+ routeId: '/layout/posts/$postId',
+ component: 'element under test',
+ loaderData: new Map([
+ ['/layout/posts/$postId', 'seeded post data'],
+ ['/layout', undefined],
+ ]),
+ }),
+ '/posts/1?tab=comments',
+ )
+ await router.load()
+
+ expect(calls).toEqual([])
+ const match = getMatch(router, '/layout/posts/$postId')
+ expect(match?.status).toBe('success')
+ expect(match?.loaderData).toBe('seeded post data')
+ // The router context is the whole context of every match.
+ expect(match?.context).toEqual({ locale: 'en' })
+ // The options derived from the URL still run.
+ expect(match?.search).toEqual({ tab: 'comments' })
+ expect(match?.params).toEqual({ postId: '1' })
+
+ const routes = router.routesById as Record
+ expect(routes['/layout/posts/$postId']!.options.component).toBe(
+ 'element under test',
+ )
+ expect(routes['/layout/posts/$postId']!.options.errorComponent).toBe(
+ undefined,
+ )
+ expect(routes['/layout']!.options.component).toBe(undefined)
+ expect(routes['__root__']!.options.component).toBe(undefined)
+ expect((routes['__root__']!.options as any).shellComponent).toBe(undefined)
+
+ await router.navigate({ to: '/lazy' })
+ expect(router.state.location.pathname).toBe('/lazy')
+ expect(loadLazyRoute).not.toHaveBeenCalled()
+ })
+
+ test('rejects an unknown route id', () => {
+ const { routeTree } = createTree()
+
+ expect(() =>
+ createIsolatedRouteTree(routeTree, {
+ routeId: '/missing',
+ component: 'element under test',
+ loaderData: new Map(),
+ }),
+ ).toThrow('The route "/missing" does not exist in the route tree')
+ })
+})
+
+describe('helpers for a test router', () => {
+ test('setTestRouterLocation moves a router that has not loaded yet', async () => {
+ const { routeTree } = createTree()
+ const router = createRouter(createTestRouteTree(routeTree), '/')
+
+ setTestRouterLocation(router, {
+ to: '/posts/$postId',
+ params: { postId: '3' },
+ search: { tab: 'comments' },
+ })
+ await router.load()
+
+ expect(router.state.location.href).toBe('/posts/3?tab=comments')
+ expect(getMatch(router, '/layout/posts/$postId')?.params).toEqual({
+ postId: '3',
+ })
+ })
+
+ test('assertRouteTestParams names the path params that are missing', () => {
+ const { routeTree } = createTree()
+ const router = createRouter(createTestRouteTree(routeTree), '/')
+
+ expect(() =>
+ assertRouteTestParams(router, '/layout/posts/$postId', undefined),
+ ).toThrow('Missing path params for route "/layout/posts/$postId": postId.')
+ expect(() =>
+ assertRouteTestParams(router, '/layout/posts/$postId', { postId: '1' }),
+ ).not.toThrow()
+ expect(() =>
+ assertRouteTestParams(router, '/lazy', undefined),
+ ).not.toThrow()
+ })
+
+ test('assertIsolatedRouteLoaded passes for a matched route', async () => {
+ const { routeTree } = createTree()
+ const router = createRouter(
+ createIsolatedRouteTree(routeTree, {
+ routeId: '/layout/posts/$postId',
+ component: 'element under test',
+ loaderData: new Map(),
+ }),
+ '/posts/1',
+ )
+ await router.load()
+
+ expect(() =>
+ assertIsolatedRouteLoaded(router, '/layout/posts/$postId'),
+ ).not.toThrow()
+ })
+
+ test('assertIsolatedRouteLoaded throws the error of a failed match', async () => {
+ const { routeTree } = createTree()
+ const router = createRouter(
+ createIsolatedRouteTree(routeTree, {
+ routeId: '/layout/posts/$postId',
+ component: 'element under test',
+ loaderData: new Map(),
+ }),
+ '/posts/1?tab=broken',
+ )
+ await router.load()
+
+ expect(() =>
+ assertIsolatedRouteLoaded(router, '/layout/posts/$postId'),
+ ).toThrow('Unknown tab')
+ })
+
+ test('assertIsolatedRouteLoaded explains a route that is not matched', async () => {
+ const { routeTree } = createTree()
+ const router = createRouter(
+ createIsolatedRouteTree(routeTree, {
+ routeId: '/layout',
+ component: 'element under test',
+ loaderData: new Map(),
+ }),
+ '/',
+ )
+ await router.load()
+
+ expect(() => assertIsolatedRouteLoaded(router, '/layout')).toThrow(
+ 'The route "/layout" is not matched at "/". Matched routes: __root__, /.',
+ )
+ })
+})
+
+describe('createTestRouterWith', () => {
+ const createRouterCore = (options: any) => createTestRouter(options)
+
+ test('creates the router with the given factory, over a copy of the tree', async () => {
+ const { routeTree, rootRoute, calls } = createTree()
+ const factory = vi.fn(createRouterCore)
+
+ const router = createTestRouterWith(factory, {
+ routeTree,
+ context: { locale: 'en' },
+ location: {
+ to: '/posts/$postId',
+ params: { postId: '3' },
+ search: { tab: 'comments' },
+ },
+ overrides: { '/layout': { loaderData: 'seeded layout data' } },
+ defaultPreloadStaleTime: 5,
+ })
+ await router.load()
+
+ expect(factory).toHaveBeenCalledTimes(1)
+ expect(router.routeTree).not.toBe(rootRoute)
+ expect(router.options.defaultPreloadStaleTime).toBe(5)
+ expect(router.state.location.href).toBe('/posts/3?tab=comments')
+ expect(getMatch(router, '/layout')?.loaderData).toBe('seeded layout data')
+ expect(calls).toContain('post.loader')
+ expect(calls).not.toContain('layout.loader')
+ })
+
+ test('uses a memory history unless one is given', () => {
+ const { routeTree } = createTree()
+
+ const withMemoryHistory = createTestRouterWith(createRouterCore, {
+ routeTree,
+ context: { locale: 'en' },
+ location: { to: '/lazy' },
+ })
+ expect(withMemoryHistory.history.location.pathname).toBe('/lazy')
+ expect(window.location.pathname).toBe('/')
+
+ const history = createMemoryHistory({ initialEntries: ['/posts/1'] })
+ const withHistory = createTestRouterWith(createRouterCore, {
+ routeTree,
+ history,
+ context: { locale: 'en' },
+ })
+ expect(withHistory.history).toBe(history)
+ expect(withHistory.history.location.pathname).toBe('/posts/1')
+ })
+})
+
+describe('createIsolatedTestRouterWith', () => {
+ const createRouterCore = (options: any) => createTestRouter(options)
+
+ test('resolves to a loaded router that renders the component in the route', async () => {
+ const { routeTree, calls } = createTree()
+
+ const router = await createIsolatedTestRouterWith(createRouterCore, {
+ routeTree,
+ route: '/layout/posts/$postId',
+ component: 'element under test',
+ params: { postId: '4' },
+ search: { tab: 'comments' },
+ context: { locale: 'en', session: 'seeded session' },
+ loaderData: {
+ '/layout': 'seeded layout data',
+ '/layout/posts/$postId': 'seeded post data',
+ },
+ defaultComponent: 'default component',
+ defaultNotFoundComponent: 'default not-found component',
+ })
+
+ expect(calls).toEqual([])
+ expect(router.state.status).toBe('idle')
+ expect(router.state.location.href).toBe('/posts/4?tab=comments')
+ const match = getMatch(router, '/layout/posts/$postId')
+ expect(match?.status).toBe('success')
+ expect(match?.loaderData).toBe('seeded post data')
+ expect(match?.context).toEqual({ locale: 'en', session: 'seeded session' })
+ expect(getMatch(router, '/layout')?.loaderData).toBe('seeded layout data')
+
+ const routes = router.routesById as Record
+ expect(routes['/layout/posts/$postId']!.options.component).toBe(
+ 'element under test',
+ )
+ // Framework options, so core types do not know them.
+ const options = router.options as Record
+ expect(options.defaultComponent).toBeUndefined()
+ expect(options.defaultNotFoundComponent).toBeUndefined()
+ expect(router.options.disableGlobalCatchBoundary).toBe(true)
+ })
+
+ test('rejects when the route cannot be reached as asked', async () => {
+ const { routeTree } = createTree()
+ const base = { routeTree, component: 'element under test' }
+
+ await expect(
+ createIsolatedTestRouterWith(createRouterCore, {
+ ...base,
+ route: '/missing',
+ }),
+ ).rejects.toThrow('The route "/missing" does not exist in the route tree')
+ await expect(
+ createIsolatedTestRouterWith(createRouterCore, {
+ ...base,
+ route: '/layout/posts/$postId',
+ }),
+ ).rejects.toThrow(
+ 'Missing path params for route "/layout/posts/$postId": postId.',
+ )
+ await expect(
+ createIsolatedTestRouterWith(createRouterCore, {
+ ...base,
+ route: '/layout/posts/$postId',
+ params: { postId: '1' },
+ search: { tab: 'broken' },
+ }),
+ ).rejects.toThrow('Unknown tab')
+ await expect(
+ createIsolatedTestRouterWith(createRouterCore, {
+ ...base,
+ route: '/layout/posts/$postId',
+ params: { postId: 'missing' },
+ }),
+ ).rejects.toThrow(
+ 'The route "/layout/posts/$postId" threw notFound() while parsing its path params at "/posts/missing".',
+ )
+ await expect(
+ createIsolatedTestRouterWith(createRouterCore, {
+ ...base,
+ route: '/layout/posts/$postId',
+ params: { postId: '1' },
+ search: { tab: 'missing' },
+ }),
+ ).rejects.toThrow(
+ 'The route "/layout/posts/$postId" threw notFound() while validating its search params at "/posts/1?tab=missing".',
+ )
+ await expect(
+ createIsolatedTestRouterWith(createRouterCore, {
+ ...base,
+ route: '/layout',
+ }),
+ ).rejects.toThrow('The route "/layout" is not matched at "/"')
+ })
+})
diff --git a/packages/router-core/vite.config.ts b/packages/router-core/vite.config.ts
index 97859dda97..c4a3111547 100644
--- a/packages/router-core/vite.config.ts
+++ b/packages/router-core/vite.config.ts
@@ -44,6 +44,7 @@ export default mergeConfig(
'./src/index.ts',
'./src/ssr/client.ts',
'./src/ssr/server.ts',
+ './src/testing/index.ts',
'./src/scroll-restoration-script/client.ts',
'./src/scroll-restoration-script/server.ts',
'./src/isServer/server.ts',
diff --git a/packages/solid-router/package.json b/packages/solid-router/package.json
index 80840069ea..ba989021fe 100644
--- a/packages/solid-router/package.json
+++ b/packages/solid-router/package.json
@@ -90,6 +90,20 @@
"default": "./dist/cjs/ssr/client.cjs"
}
},
+ "./testing": {
+ "solid": {
+ "types": "./dist/source/testing.d.ts",
+ "default": "./dist/source/testing.js"
+ },
+ "import": {
+ "types": "./dist/esm/testing.d.ts",
+ "default": "./dist/esm/testing.js"
+ },
+ "require": {
+ "types": "./dist/cjs/testing.d.cts",
+ "default": "./dist/cjs/testing.cjs"
+ }
+ },
"./package.json": "./package.json"
},
"sideEffects": false,
diff --git a/packages/solid-router/src/testing.ts b/packages/solid-router/src/testing.ts
new file mode 100644
index 0000000000..5c023a8800
--- /dev/null
+++ b/packages/solid-router/src/testing.ts
@@ -0,0 +1,165 @@
+import {
+ createIsolatedTestRouterWith,
+ createTestRouterWith,
+} from '@tanstack/router-core/testing'
+import { createRouter } from './router'
+import type { JSX } from 'solid-js'
+import type { RouterHistory } from '@tanstack/history'
+import type { AnyRoute, TrailingSlashOption } from '@tanstack/router-core'
+import type {
+ RouteTestOverrides as CoreRouteTestOverrides,
+ IsolatedTestRouterOptions,
+ TestRouterOptions,
+} from '@tanstack/router-core/testing'
+import type {
+ ErrorRouteComponent,
+ NotFoundRouteComponent,
+ RouteComponent,
+} from './route'
+import type { Router } from './router'
+
+export type {
+ IsolatedRouteState,
+ RouteTestBeforeLoadFn,
+ RouteTestContextFn,
+ RouteTestLoaderFn,
+} from '@tanstack/router-core/testing'
+
+/** The component options a test can replace on a route. */
+export interface RouteTestComponents {
+ component?: RouteComponent
+ pendingComponent?: RouteComponent
+ errorComponent?: false | null | undefined | ErrorRouteComponent
+ notFoundComponent?: NotFoundRouteComponent
+}
+
+/**
+ * Overrides by route id, typed from the route tree. The root route's id is
+ * `rootRouteId`, used as a computed key: `{ [rootRouteId]: { ... } }`.
+ */
+export type RouteTestOverrides =
+ CoreRouteTestOverrides
+
+/** The options of `createTestRouter`: those of `createRouter`, plus `location` and `overrides`. */
+export type CreateTestRouterOptions<
+ TRouteTree extends AnyRoute,
+ TLocation = unknown,
+ TTrailingSlashOption extends TrailingSlashOption = 'never',
+ TDefaultStructuralSharingOption extends boolean = false,
+ TRouterHistory extends RouterHistory = RouterHistory,
+ TDehydrated extends Record = Record,
+> = TestRouterOptions<
+ TRouteTree,
+ TLocation,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ TRouterHistory,
+ TDehydrated,
+ RouteTestComponents
+>
+
+/**
+ * The options of `createIsolatedTestRouter`. Solid evaluates JSX right away,
+ * so the element under test is passed as a function: `() => `.
+ */
+export type CreateIsolatedTestRouterOptions<
+ TRouteTree extends AnyRoute,
+ TId,
+ TTrailingSlashOption extends TrailingSlashOption = 'never',
+ TDefaultStructuralSharingOption extends boolean = false,
+> = IsolatedTestRouterOptions<
+ TRouteTree,
+ TId,
+ () => JSX.Element,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption
+>
+
+/**
+ * Creates a router for a test, over a copy of the route tree. It takes the
+ * options of `createRouter`, plus `location` and `overrides`. Every route runs
+ * the application's own options unless `overrides` replaces them. Without a
+ * `history`, the router uses a memory history.
+ *
+ * The router has not loaded yet. Render it with `RouterProvider`, or call
+ * `router.load()` first.
+ *
+ * ```tsx
+ * const router = createTestRouter({
+ * routeTree,
+ * context: { queryClient },
+ * location: { to: '/posts/$postId', params: { postId: '1' } },
+ * overrides: { '/posts/$postId': { loaderData: { post } } },
+ * })
+ * render(() => )
+ * ```
+ */
+export function createTestRouter<
+ TRouteTree extends AnyRoute,
+ const TLocation = unknown,
+ TTrailingSlashOption extends TrailingSlashOption = 'never',
+ TDefaultStructuralSharingOption extends boolean = false,
+ TRouterHistory extends RouterHistory = RouterHistory,
+ TDehydrated extends Record = Record,
+>(
+ options: CreateTestRouterOptions<
+ TRouteTree,
+ TLocation,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ TRouterHistory,
+ TDehydrated
+ >,
+): Router<
+ TRouteTree,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ TRouterHistory,
+ TDehydrated
+> {
+ return createTestRouterWith(createRouter, options as any) as any
+}
+
+/**
+ * Creates a router that renders one element inside one route, with the state
+ * the test supplies. It resolves once the router has loaded, so the first
+ * render of `` is complete.
+ *
+ * No `context`, `beforeLoad` or `loader` of any route runs, and no route
+ * component renders. The options are typed from the route: they ask for the
+ * context and the loader data those options would have produced.
+ *
+ * ```tsx
+ * const router = await createIsolatedTestRouter({
+ * routeTree,
+ * route: '/posts/$postId',
+ * element: () => ,
+ * params: { postId: '1' },
+ * loaderData: { '/posts/$postId': { post } },
+ * })
+ * render(() => )
+ * ```
+ */
+export function createIsolatedTestRouter<
+ TRouteTree extends AnyRoute,
+ // `IsolatedTestRouterOptions` checks that `route` is a route id of the tree.
+ const TId extends string,
+ TTrailingSlashOption extends TrailingSlashOption = 'never',
+ TDefaultStructuralSharingOption extends boolean = false,
+>(
+ options: CreateIsolatedTestRouterOptions<
+ TRouteTree,
+ TId,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption
+ >,
+): Promise<
+ Router
+> {
+ const { element, ...state } = options as any
+ // The function that creates the element is itself a Solid component.
+ return createIsolatedTestRouterWith(createRouter, {
+ ...state,
+ component: element,
+ }) as any
+}
diff --git a/packages/solid-router/tests/testing.test-d.tsx b/packages/solid-router/tests/testing.test-d.tsx
new file mode 100644
index 0000000000..7eddaa4114
--- /dev/null
+++ b/packages/solid-router/tests/testing.test-d.tsx
@@ -0,0 +1,108 @@
+import { describe, expectTypeOf, test } from 'vitest'
+import { createRootRouteWithContext, createRoute, rootRouteId } from '../src'
+import { createIsolatedTestRouter, createTestRouter } from '../src/testing'
+import type { Router } from '../src'
+import type { IsolatedRouteState } from '../src/testing'
+
+interface User {
+ id: string
+}
+
+const rootRoute = createRootRouteWithContext<{ locale: string }>()({
+ beforeLoad: (): { session: { user: User | null } } => ({
+ session: { user: null },
+ }),
+})
+
+const authedRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ id: '_authed',
+ beforeLoad: ({ context }) => ({ user: context.session.user as User }),
+ loader: () => ({ unreadCount: 1 }),
+})
+
+const postRoute = createRoute({
+ getParentRoute: () => authedRoute,
+ path: '/posts/$postId',
+ loader: ({ params }) => ({ post: { id: params.postId } }),
+})
+
+const routeTree = rootRoute.addChildren([authedRoute.addChildren([postRoute])])
+
+type RouteTree = typeof routeTree
+
+type RequiredKeys = {
+ [K in keyof T]-?: {} extends Pick ? never : K
+}[keyof T]
+
+const postState = {
+ routeTree,
+ route: '/_authed/posts/$postId',
+ element: () => ,
+ params: { postId: '1' },
+ context: { locale: 'en', session: { user: null }, user: { id: '1' } },
+ loaderData: {
+ '/_authed': { unreadCount: 1 },
+ '/_authed/posts/$postId': { post: { id: '1' } },
+ },
+} as const
+
+describe('createIsolatedTestRouter', () => {
+ test('asks for everything the route promises to its components', () => {
+ type PostState = IsolatedRouteState
+
+ expectTypeOf>().toEqualTypeOf<
+ 'route' | 'params' | 'context' | 'loaderData'
+ >()
+ expectTypeOf>().toEqualTypeOf<
+ '/_authed' | '/_authed/posts/$postId'
+ >()
+ })
+
+ test('resolves to the Solid router type', () => {
+ expectTypeOf(createIsolatedTestRouter(postState)).toEqualTypeOf<
+ Promise>
+ >()
+ })
+
+ test('takes the element as a function, since Solid evaluates JSX right away', () => {
+ const elementNotFunction = { ...postState, element: }
+ // @ts-expect-error the element has to be a function that returns JSX
+ void createIsolatedTestRouter(elementNotFunction)
+ })
+
+ test('rejects state that is incomplete', () => {
+ const withoutAncestorLoaderData = {
+ ...postState,
+ loaderData: { '/_authed/posts/$postId': { post: { id: '1' } } },
+ } as const
+ // @ts-expect-error the loader data of `/_authed` is missing
+ void createIsolatedTestRouter(withoutAncestorLoaderData)
+ })
+})
+
+describe('createTestRouter', () => {
+ test('returns the Solid router type and types the overrides', () => {
+ expectTypeOf(
+ createTestRouter({
+ routeTree,
+ context: { locale: 'en' },
+ location: { to: '/posts/$postId', params: { postId: '1' } },
+ overrides: {
+ [rootRouteId]: { routeContext: { session: { user: { id: '1' } } } },
+ '/_authed/posts/$postId': {
+ loader: ({ params }) => ({ post: { id: params.postId } }),
+ },
+ },
+ }),
+ ).toEqualTypeOf>()
+
+ const wrongSeed = {
+ routeTree,
+ context: { locale: 'en' },
+ overrides: { '/_authed': { loaderData: { unreadCount: 'many' } } },
+ } as const
+ // @ts-expect-error `unreadCount` is a number
+ createTestRouter(wrongSeed)
+ })
+})
diff --git a/packages/solid-router/tests/testing.test.tsx b/packages/solid-router/tests/testing.test.tsx
new file mode 100644
index 0000000000..6e86a0a355
--- /dev/null
+++ b/packages/solid-router/tests/testing.test.tsx
@@ -0,0 +1,234 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library'
+import { afterEach, describe, expect, test } from 'vitest'
+import {
+ Link,
+ Outlet,
+ RouterProvider,
+ createRootRouteWithContext,
+ createRoute,
+ redirect,
+ rootRouteId,
+} from '../src'
+import { createIsolatedTestRouter, createTestRouter } from '../src/testing'
+
+afterEach(() => {
+ cleanup()
+})
+
+interface User {
+ id: string
+ name: string
+}
+
+interface Session {
+ user: User | null
+}
+
+const realUser: User = { id: 'real', name: 'Real user' }
+const testUser: User = { id: 'test', name: 'Test user' }
+
+function createApp() {
+ const calls: Array = []
+
+ const rootRoute = createRootRouteWithContext<{ locale: string }>()({
+ beforeLoad: (): { session: Session } => {
+ calls.push('root.beforeLoad')
+ return { session: { user: realUser } }
+ },
+ component: () => (
+
+ ),
+ })
+
+ 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: () => (
+
+ ),
+ })
+
+ 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 (
+
+ )
+ }
+
+ 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) => (
+
+ ),
+ })
+ render(() => )
+
+ expect(screen.getByLabelText('Providers')).toHaveTextContent('Element')
+ })
+})
diff --git a/packages/solid-router/vite.config.ts b/packages/solid-router/vite.config.ts
index 3c9e49ec37..e562bfc7a9 100644
--- a/packages/solid-router/vite.config.ts
+++ b/packages/solid-router/vite.config.ts
@@ -59,6 +59,7 @@ export default defineConfig((env) =>
'./src/index.dev.tsx',
'./src/ssr/client.ts',
'./src/ssr/server.ts',
+ './src/testing.ts',
],
srcDir: './src',
}),
diff --git a/packages/vue-router/package.json b/packages/vue-router/package.json
index 93ae8fdeed..e7a59e5d13 100644
--- a/packages/vue-router/package.json
+++ b/packages/vue-router/package.json
@@ -59,6 +59,12 @@
"default": "./dist/esm/ssr/client.js"
}
},
+ "./testing": {
+ "import": {
+ "types": "./dist/esm/testing.d.ts",
+ "default": "./dist/esm/testing.js"
+ }
+ },
"./package.json": "./package.json"
},
"sideEffects": false,
diff --git a/packages/vue-router/src/testing.ts b/packages/vue-router/src/testing.ts
new file mode 100644
index 0000000000..2d9739fb5d
--- /dev/null
+++ b/packages/vue-router/src/testing.ts
@@ -0,0 +1,166 @@
+import {
+ createIsolatedTestRouterWith,
+ createTestRouterWith,
+} from '@tanstack/router-core/testing'
+import { createRouter } from './router'
+import type { VNode } from 'vue'
+import type { RouterHistory } from '@tanstack/history'
+import type { AnyRoute, TrailingSlashOption } from '@tanstack/router-core'
+import type {
+ RouteTestOverrides as CoreRouteTestOverrides,
+ IsolatedTestRouterOptions,
+ TestRouterOptions,
+} from '@tanstack/router-core/testing'
+import type {
+ ErrorRouteComponent,
+ NotFoundRouteComponent,
+ RouteComponent,
+ VueSFC,
+} from './route'
+import type { Router } from './router'
+
+export type {
+ IsolatedRouteState,
+ RouteTestBeforeLoadFn,
+ RouteTestContextFn,
+ RouteTestLoaderFn,
+} from '@tanstack/router-core/testing'
+
+/** The component options a test can replace on a route. */
+export interface RouteTestComponents {
+ component?: RouteComponent | VueSFC
+ pendingComponent?: RouteComponent | VueSFC
+ errorComponent?: false | null | undefined | ErrorRouteComponent | VueSFC
+ notFoundComponent?: NotFoundRouteComponent | VueSFC
+}
+
+/**
+ * Overrides by route id, typed from the route tree. The root route's id is
+ * `rootRouteId`, used as a computed key: `{ [rootRouteId]: { ... } }`.
+ */
+export type RouteTestOverrides =
+ CoreRouteTestOverrides
+
+/** The options of `createTestRouter`: those of `createRouter`, plus `location` and `overrides`. */
+export type CreateTestRouterOptions<
+ TRouteTree extends AnyRoute,
+ TLocation = unknown,
+ TTrailingSlashOption extends TrailingSlashOption = 'never',
+ TDefaultStructuralSharingOption extends boolean = false,
+ TRouterHistory extends RouterHistory = RouterHistory,
+ TDehydrated extends Record = Record,
+> = TestRouterOptions<
+ TRouteTree,
+ TLocation,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ TRouterHistory,
+ TDehydrated,
+ RouteTestComponents
+>
+
+/**
+ * The options of `createIsolatedTestRouter`. The element under test is a
+ * vnode, for example `` with Vue JSX or `h(PostHeader)`.
+ */
+export type CreateIsolatedTestRouterOptions<
+ TRouteTree extends AnyRoute,
+ TId,
+ TTrailingSlashOption extends TrailingSlashOption = 'never',
+ TDefaultStructuralSharingOption extends boolean = false,
+> = IsolatedTestRouterOptions<
+ TRouteTree,
+ TId,
+ VNode,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption
+>
+
+/**
+ * Creates a router for a test, over a copy of the route tree. It takes the
+ * options of `createRouter`, plus `location` and `overrides`. Every route runs
+ * the application's own options unless `overrides` replaces them. Without a
+ * `history`, the router uses a memory history.
+ *
+ * The router has not loaded yet. Render it with `RouterProvider`, or call
+ * `router.load()` first.
+ *
+ * ```tsx
+ * const router = createTestRouter({
+ * routeTree,
+ * context: { queryClient },
+ * location: { to: '/posts/$postId', params: { postId: '1' } },
+ * overrides: { '/posts/$postId': { loaderData: { post } } },
+ * })
+ * render()
+ * ```
+ */
+export function createTestRouter<
+ TRouteTree extends AnyRoute,
+ const TLocation = unknown,
+ TTrailingSlashOption extends TrailingSlashOption = 'never',
+ TDefaultStructuralSharingOption extends boolean = false,
+ TRouterHistory extends RouterHistory = RouterHistory,
+ TDehydrated extends Record = Record,
+>(
+ options: CreateTestRouterOptions<
+ TRouteTree,
+ TLocation,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ TRouterHistory,
+ TDehydrated
+ >,
+): Router<
+ TRouteTree,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption,
+ TRouterHistory,
+ TDehydrated
+> {
+ return createTestRouterWith(createRouter, options as any) as any
+}
+
+/**
+ * Creates a router that renders one element inside one route, with the state
+ * the test supplies. It resolves once the router has loaded, so the first
+ * render of `` is complete.
+ *
+ * No `context`, `beforeLoad` or `loader` of any route runs, and no route
+ * component renders. The options are typed from the route: they ask for the
+ * context and the loader data those options would have produced.
+ *
+ * ```tsx
+ * const router = await createIsolatedTestRouter({
+ * routeTree,
+ * route: '/posts/$postId',
+ * element: ,
+ * params: { postId: '1' },
+ * loaderData: { '/posts/$postId': { post } },
+ * })
+ * render()
+ * ```
+ */
+export function createIsolatedTestRouter<
+ TRouteTree extends AnyRoute,
+ // `IsolatedTestRouterOptions` checks that `route` is a route id of the tree.
+ const TId extends string,
+ TTrailingSlashOption extends TrailingSlashOption = 'never',
+ TDefaultStructuralSharingOption extends boolean = false,
+>(
+ options: CreateIsolatedTestRouterOptions<
+ TRouteTree,
+ TId,
+ TTrailingSlashOption,
+ TDefaultStructuralSharingOption
+ >,
+): Promise<
+ Router
+> {
+ const { element, ...state } = options as any
+ // A functional component that renders the vnode under test.
+ return createIsolatedTestRouterWith(createRouter, {
+ ...state,
+ component: () => element,
+ }) as any
+}
diff --git a/packages/vue-router/tests/testing.test-d.tsx b/packages/vue-router/tests/testing.test-d.tsx
new file mode 100644
index 0000000000..dfdc32f630
--- /dev/null
+++ b/packages/vue-router/tests/testing.test-d.tsx
@@ -0,0 +1,102 @@
+import { describe, expectTypeOf, test } from 'vitest'
+import { createRootRouteWithContext, createRoute, rootRouteId } from '../src'
+import { createIsolatedTestRouter, createTestRouter } from '../src/testing'
+import type { Router } from '../src'
+import type { IsolatedRouteState } from '../src/testing'
+
+interface User {
+ id: string
+}
+
+const rootRoute = createRootRouteWithContext<{ locale: string }>()({
+ beforeLoad: (): { session: { user: User | null } } => ({
+ session: { user: null },
+ }),
+})
+
+const authedRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ id: '_authed',
+ beforeLoad: ({ context }) => ({ user: context.session.user as User }),
+ loader: () => ({ unreadCount: 1 }),
+})
+
+const postRoute = createRoute({
+ getParentRoute: () => authedRoute,
+ path: '/posts/$postId',
+ loader: ({ params }) => ({ post: { id: params.postId } }),
+})
+
+const routeTree = rootRoute.addChildren([authedRoute.addChildren([postRoute])])
+
+type RouteTree = typeof routeTree
+
+type RequiredKeys = {
+ [K in keyof T]-?: {} extends Pick ? never : K
+}[keyof T]
+
+const postState = {
+ routeTree,
+ route: '/_authed/posts/$postId',
+ element: ,
+ params: { postId: '1' },
+ context: { locale: 'en', session: { user: null }, user: { id: '1' } },
+ loaderData: {
+ '/_authed': { unreadCount: 1 },
+ '/_authed/posts/$postId': { post: { id: '1' } },
+ },
+} as const
+
+describe('createIsolatedTestRouter', () => {
+ test('asks for everything the route promises to its components', () => {
+ type PostState = IsolatedRouteState
+
+ expectTypeOf>().toEqualTypeOf<
+ 'route' | 'params' | 'context' | 'loaderData'
+ >()
+ expectTypeOf>().toEqualTypeOf<
+ '/_authed' | '/_authed/posts/$postId'
+ >()
+ })
+
+ test('resolves to the Vue router type', () => {
+ expectTypeOf(createIsolatedTestRouter(postState)).toEqualTypeOf<
+ Promise>
+ >()
+ })
+
+ test('rejects state that is incomplete', () => {
+ const withoutAncestorLoaderData = {
+ ...postState,
+ loaderData: { '/_authed/posts/$postId': { post: { id: '1' } } },
+ } as const
+ // @ts-expect-error the loader data of `/_authed` is missing
+ void createIsolatedTestRouter(withoutAncestorLoaderData)
+ })
+})
+
+describe('createTestRouter', () => {
+ test('returns the Vue router type and types the overrides', () => {
+ expectTypeOf(
+ createTestRouter({
+ routeTree,
+ context: { locale: 'en' },
+ location: { to: '/posts/$postId', params: { postId: '1' } },
+ overrides: {
+ [rootRouteId]: { routeContext: { session: { user: { id: '1' } } } },
+ '/_authed/posts/$postId': {
+ loader: ({ params }) => ({ post: { id: params.postId } }),
+ },
+ },
+ }),
+ ).toEqualTypeOf>()
+
+ const wrongSeed = {
+ routeTree,
+ context: { locale: 'en' },
+ overrides: { '/_authed': { loaderData: { unreadCount: 'many' } } },
+ } as const
+ // @ts-expect-error `unreadCount` is a number
+ createTestRouter(wrongSeed)
+ })
+})
diff --git a/packages/vue-router/tests/testing.test.tsx b/packages/vue-router/tests/testing.test.tsx
new file mode 100644
index 0000000000..f85b214cba
--- /dev/null
+++ b/packages/vue-router/tests/testing.test.tsx
@@ -0,0 +1,245 @@
+import { afterEach, describe, expect, test } from 'vitest'
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@testing-library/vue'
+import { defineComponent } from 'vue'
+import {
+ Link,
+ Outlet,
+ RouterProvider,
+ createRootRouteWithContext,
+ createRoute,
+ redirect,
+ rootRouteId,
+} from '../src'
+import { createIsolatedTestRouter, createTestRouter } from '../src/testing'
+
+afterEach(() => {
+ cleanup()
+})
+
+interface User {
+ id: string
+ name: string
+}
+
+interface Session {
+ user: User | null
+}
+
+const realUser: User = { id: 'real', name: 'Real user' }
+const testUser: User = { id: 'test', name: 'Test user' }
+
+function createApp() {
+ const calls: Array = []
+
+ const rootRoute = createRootRouteWithContext<{ locale: string }>()({
+ beforeLoad: (): { session: Session } => {
+ calls.push('root.beforeLoad')
+ return { session: { user: realUser } }
+ },
+ component: () => (
+
+ ),
+ })
+
+ 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: () => (
+
+ ),
+ })
+
+ 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 () => (
+
+ )
+ },
+ })
+
+ 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 () => (
+
+ )
+ },
+ })
+
+ const router = await createIsolatedTestRouter({
+ routeTree: app.routeTree,
+ route: '/login',
+ element: Element
,
+ context: { locale: 'en', session: { user: null } },
+ // Vue renders `Wrap` with a default slot, as in RouterProvider.test.tsx.
+ Wrap: Providers as any,
+ })
+ render()
+
+ expect(await screen.findByLabelText('Providers')).toHaveTextContent(
+ 'Element',
+ )
+ })
+})
diff --git a/packages/vue-router/vite.config.ts b/packages/vue-router/vite.config.ts
index 13928e0a1a..6355c72f41 100644
--- a/packages/vue-router/vite.config.ts
+++ b/packages/vue-router/vite.config.ts
@@ -37,6 +37,7 @@ export default mergeConfig(
'./src/index.dev.tsx',
'./src/ssr/client.ts',
'./src/ssr/server.ts',
+ './src/testing.ts',
],
srcDir: './src',
cjs: false,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4328f4fab6..a64e1f009e 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1611,6 +1611,43 @@ importers:
specifier: ^8.3.4
version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)
+ e2e/react-router/route-testing:
+ dependencies:
+ '@tanstack/react-router':
+ specifier: workspace:*
+ version: link:../../../packages/react-router
+ '@tanstack/router-plugin':
+ specifier: workspace:*
+ version: link:../../../packages/router-plugin
+ react:
+ specifier: ~19.2.9
+ version: 19.2.9
+ react-dom:
+ specifier: ~19.2.9
+ version: 19.2.9(react@19.2.9)
+ devDependencies:
+ '@testing-library/react':
+ specifier: 'catalog:'
+ version: 16.3.0(@testing-library/dom@10.4.1)(@types/react-dom@19.2.3(@types/react@19.2.9))(@types/react@19.2.9)(react-dom@19.2.9(react@19.2.9))(react@19.2.9)
+ '@types/react':
+ specifier: ^19.2.8
+ version: 19.2.9
+ '@types/react-dom':
+ specifier: ^19.2.3
+ version: 19.2.3(@types/react@19.2.9)
+ '@vitejs/plugin-react':
+ specifier: 'catalog:'
+ version: 6.0.1(@rolldown/plugin-babel@0.2.3(@babel/core@7.29.7(supports-color@10.2.2))(rolldown@1.2.13)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)))(babel-plugin-react-compiler@1.0.0)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))
+ jsdom:
+ specifier: 'catalog:'
+ version: 25.0.1(supports-color@10.2.2)
+ vite:
+ specifier: ^8.3.4
+ version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)
+ vitest:
+ specifier: 'catalog:'
+ version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))
+
e2e/react-router/rspack-basic-file-based:
dependencies:
'@tanstack/react-router':
@@ -6844,6 +6881,34 @@ importers:
specifier: ^8.3.4
version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)
+ e2e/vue-router/route-testing:
+ dependencies:
+ '@tanstack/router-plugin':
+ specifier: workspace:*
+ version: link:../../../packages/router-plugin
+ '@tanstack/vue-router':
+ specifier: workspace:*
+ version: link:../../../packages/vue-router
+ vue:
+ specifier: 'catalog:'
+ version: 3.5.25(typescript@6.0.2)
+ devDependencies:
+ '@testing-library/vue':
+ specifier: ^8.1.0
+ version: 8.1.0(@vue/compiler-sfc@3.5.25)(vue@3.5.25(typescript@6.0.2))
+ '@vitejs/plugin-vue-jsx':
+ specifier: 'catalog:'
+ version: 4.2.0(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vue@3.5.25(typescript@6.0.2))
+ jsdom:
+ specifier: 'catalog:'
+ version: 25.0.1(supports-color@10.2.2)
+ vite:
+ specifier: ^8.3.4
+ version: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)
+ vitest:
+ specifier: 'catalog:'
+ version: 5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))
+
e2e/vue-router/rspack-basic-file-based:
dependencies:
'@tanstack/vue-router':
@@ -35729,6 +35794,15 @@ snapshots:
optionalDependencies:
'@vue/compiler-sfc': 3.5.25
+ '@testing-library/vue@8.1.0(@vue/compiler-sfc@3.5.25)(vue@3.5.25(typescript@6.0.2))':
+ dependencies:
+ '@babel/runtime': 7.26.7
+ '@testing-library/dom': 9.3.4
+ '@vue/test-utils': 2.4.6
+ vue: 3.5.25(typescript@6.0.2)
+ optionalDependencies:
+ '@vue/compiler-sfc': 3.5.25
+
'@trpc/client@11.4.3(@trpc/server@11.4.3(@typescript/typescript6@6.0.2))(@typescript/typescript6@6.0.2)':
dependencies:
'@trpc/server': 11.4.3(@typescript/typescript6@6.0.2)
@@ -36631,6 +36705,17 @@ snapshots:
vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)
vitefu: 1.1.3(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))
+ '@vitejs/plugin-vue-jsx@4.2.0(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vue@3.5.25(typescript@6.0.2))':
+ dependencies:
+ '@babel/core': 7.29.7(supports-color@10.2.2)
+ '@babel/plugin-transform-typescript': 7.28.6(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)
+ '@rolldown/pluginutils': 1.0.1
+ '@vue/babel-plugin-jsx': 1.5.0(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2)
+ vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)
+ vue: 3.5.25(typescript@6.0.2)
+ transitivePeerDependencies:
+ - supports-color
+
'@vitejs/plugin-vue-jsx@4.2.0(supports-color@10.2.2)(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))(vue@3.5.25(@typescript/typescript6@6.0.2))':
dependencies:
'@babel/core': 7.29.7(supports-color@10.2.2)
@@ -36774,6 +36859,16 @@ snapshots:
msw: 2.15.0(@types/node@25.0.9)(typescript@5.9.2)
vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)
+ '@vitest/mocker@5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))':
+ dependencies:
+ '@jridgewell/trace-mapping': 0.3.31
+ '@vitest/spy': 5.0.4
+ estree-walker: 3.0.3
+ magic-string: 1.4.3
+ optionalDependencies:
+ msw: 2.15.0(@types/node@25.0.9)(typescript@6.0.2)
+ vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)
+
'@vitest/pretty-format@4.1.4':
dependencies:
tinyrainbow: 3.2.0
@@ -40400,7 +40495,7 @@ snapshots:
cssstyle: 4.2.1
data-urls: 5.0.0
decimal.js: 10.6.0
- form-data: 4.0.5
+ form-data: 4.0.6
html-encoding-sniffer: 4.0.0
http-proxy-agent: 7.0.2(supports-color@10.2.2)
https-proxy-agent: 7.0.6(supports-color@10.2.2)
@@ -40416,7 +40511,7 @@ snapshots:
whatwg-encoding: 3.1.1
whatwg-mimetype: 4.0.0
whatwg-url: 14.1.0
- ws: 8.20.0
+ ws: 8.21.0
xml-name-validator: 5.0.0
transitivePeerDependencies:
- bufferutil
@@ -41095,6 +41190,32 @@ snapshots:
- '@types/node'
optional: true
+ msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2):
+ dependencies:
+ '@inquirer/confirm': 6.3.2(@types/node@25.0.9)
+ '@mswjs/interceptors': 0.41.9
+ '@open-draft/deferred-promise': 3.0.0
+ '@types/statuses': 2.0.6
+ cookie: 1.1.1
+ graphql: 16.14.2
+ headers-polyfill: 5.0.1
+ is-node-process: 1.2.0
+ outvariant: 1.4.3
+ path-to-regexp: 6.3.0
+ picocolors: 1.1.1
+ rettime: 0.11.11
+ statuses: 2.0.2
+ strict-event-emitter: 0.5.1
+ tough-cookie: 6.0.1
+ type-fest: 5.9.0
+ until-async: 3.0.2
+ yargs: 17.7.2
+ optionalDependencies:
+ typescript: 6.0.2
+ transitivePeerDependencies:
+ - '@types/node'
+ optional: true
+
msw@2.7.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2):
dependencies:
'@bundled-es-modules/cookie': 2.0.1
@@ -44200,6 +44321,30 @@ snapshots:
transitivePeerDependencies:
- msw
+ vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@25.0.1(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)):
+ dependencies:
+ '@types/chai': 5.2.2
+ '@vitest/mocker': 5.0.4(msw@2.15.0(@types/node@25.0.9)(typescript@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0))
+ chai: 6.3.0
+ es-module-lexer: 2.3.2
+ expect-type: 1.4.0
+ magic-string: 1.4.3
+ obug: 3.0.0
+ picomatch: 4.0.7
+ std-env: 4.3.0
+ tinybench: 6.2.2
+ tinyexec: 1.3.1
+ tinyglobby: 0.2.17
+ vite: 8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.105.1)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)
+ why-is-node-running: 3.2.1
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.1
+ '@types/node': 25.0.9
+ '@vitest/ui': 5.0.4(vitest@5.0.4)
+ jsdom: 25.0.1(supports-color@10.2.2)
+ transitivePeerDependencies:
+ - msw
+
vitest@5.0.4(@opentelemetry/api@1.9.1)(@types/node@25.0.9)(@vitest/ui@5.0.4)(jsdom@27.0.0(supports-color@10.2.2))(msw@2.15.0(@types/node@25.0.9)(@typescript/typescript6@6.0.2))(vite@8.3.4(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)):
dependencies:
'@types/chai': 5.2.2