Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/react-start-prebundle-store-path.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/react-start': patch
---

fix: Vite pre-bundles `@tanstack/react-store` for a project that depends on `@tanstack/react-start` but not on `@tanstack/react-router` itself. Start named the dependency by a path through `@tanstack/react-router`, which only resolves from a project that depends on the router. In such a project Vite warned "Failed to resolve dependency: @tanstack/react-router > @tanstack/react-store", and a browser failed to load the store's CommonJS dependency (`use-sync-external-store`).
18 changes: 18 additions & 0 deletions .changeset/start-vitest-test-runs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
'@tanstack/start-plugin-core': minor
'@tanstack/react-start': minor
'@tanstack/solid-start': minor
'@tanstack/vue-start': minor
'@tanstack/router-plugin': minor
'@tanstack/router-generator': minor
---

Start's Vite plugin can be used in a Vitest config. When Vitest resolves the config to run tests, the plugin compiles the code as it does in the app (`createServerFn`, `createIsomorphicFn`, `createServerOnlyFn`, `createClientOnlyFn`, the server-only route options), for the client in browser mode and in jsdom or happy-dom, and for the server in the Node environment. It does not set up the app's dev server, preview server or build.

- A project needs no router entry and no routes. A package that only uses Start's compile-time APIs used to fail with "Could not resolve entry for router entry".
- The route tree is generated once, when Vitest starts, and only for a project with a router entry and a root route. It is not regenerated while Vitest watches.
- A test run never writes route files: a route file with an outdated route path and an empty route file are left as they are, with a warning.
- A module that calls `createFileRoute`, `createRootRoute` or `createRootRouteWithContext` loses its `server`, `ssr` and `headers` options in client code even when the route generator does not know the module.
- It needs Vitest 5.1.1 or later, which `@tanstack/start-plugin-core` and the framework packages declare as an optional peer dependency. Before, Vitest's translation of the wildcards in `resolve.noExternal` missed a package name with a dash, so in a project that installs Start from the registry, jsdom, happy-dom and Node tests ran `@tanstack/start-client-core` without the Start compiler.

For this, `Generator` of `@tanstack/router-generator` takes `writeRouteFiles: false`, and `tanstackRouterGenerator` and `tanStackRouterCodeSplitter` of `@tanstack/router-plugin/vite` take options for the plugin that embeds them.
4 changes: 4 additions & 0 deletions docs/start/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,10 @@
{
"label": "Server Routes",
"to": "framework/react/guide/server-routes"
},
{
"label": "Testing",
"to": "framework/react/guide/testing"
}
]
},
Expand Down
127 changes: 127 additions & 0 deletions docs/start/framework/react/guide/testing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
---
id: testing
title: Testing
---

> **Experimental:** Start's support for test runners is experimental and subject to change. It works with Vitest 5.1.1 or later.

Start's Vite plugin compiles your code for the environment it runs in. In client code a server function becomes a request to the server, and an isomorphic function keeps its client implementation. Code that only the server uses is removed, together with its imports. Tests need the same compilation: without it, a client test imports your database client and every other module that only the server can load.

When Vitest loads a config that contains `tanstackStart()`, the plugin compiles your code as it does in the app. It leaves out the parts that serve or build the app, so a test run starts no dev server and needs no built output.

The examples on this page use React. `@tanstack/solid-start` and `@tanstack/vue-start` work the same way.

## Setup

Add `tanstackStart()` to the config your tests use. An app can use one `vite.config.ts` for the app and for its tests:

```ts title="vite.config.ts"
import { defineConfig } from 'vitest/config'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import react from '@vitejs/plugin-react'
import { playwright } from '@vitest/browser-playwright'

export default defineConfig({
plugins: [tanstackStart(), react()],
test: {
projects: [
{
extends: true,
test: {
name: 'client',
include: ['tests/**/*.client.test.{ts,tsx}'],
browser: {
enabled: true,
provider: playwright(),
instances: [{ browser: 'chromium' }],
},
},
},
{
extends: true,
test: {
name: 'server',
environment: 'node',
include: ['tests/**/*.server.test.ts'],
},
},
],
},
})
```

The two projects and the file names are a convention of this example. A test file is compiled for the environment its project runs in.

A package that only uses Start's APIs, such as a shared library of server functions, uses the same config. In a test run the plugin does not ask for a router entry or for routes.

Start treats a run as a test run when Vitest resolves the config in its default mode, `test`. With another mode (`vitest --mode staging`) the plugin sets up the app's dev server as usual.

## Which code a test gets

| Test environment | Code the test gets |
| ----------------------------------------------------------------------- | ------------------ |
| [Browser mode](https://vitest.dev/guide/browser/), `jsdom`, `happy-dom` | Client |
| `node` | Server |

Take a module with an isomorphic function whose server implementation reads a secret:

```ts title="src/runtime.ts"
import { createIsomorphicFn } from '@tanstack/react-start'
import { readSecret } from './secrets.server'

export const describeRuntime = createIsomorphicFn()
.server(() => `server with ${readSecret()}`)
.client(() => 'client')
```

In a client test `describeRuntime()` returns `'client'`, and `./secrets.server` is never loaded. In a server test it runs the server implementation.

`createServerOnlyFn` and `createClientOnlyFn` behave as in the app too: the function runs in its own environment and throws in the other one.

## Routes in a test run

A test can import a route file or the generated route tree.

The route tree is generated once, when Vitest starts, and only for a project that has a router entry and a root route. It is not regenerated while Vitest watches. After you add, move or delete a route file, restart Vitest.

A test run never writes to your route files. The dev server fills in an empty route file and corrects the path in a file you moved. A test run leaves both as they are and logs a warning.

In client code a route loses its `server`, `ssr` and `headers` options, as in the app. That holds for every module that calls `createFileRoute`, `createRootRoute` or `createRootRouteWithContext`, including one outside the routes directory.

## Server functions in client tests

A client test has no server, so a server function call in client code has no one to answer it. Replace the server function with a module mock. `importOriginal` keeps the other exports of the module:

```tsx title="tests/post-title.client.test.tsx"
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen } from '@testing-library/react'
import { expect, test, vi } from 'vitest'
import { PostTitle } from '../src/components/PostTitle'
import { fetchPost } from '../src/posts'

vi.mock('../src/posts', async (importOriginal) => ({
...(await importOriginal<typeof import('../src/posts')>()),
fetchPost: vi.fn(async ({ data }: { data: string }) => ({
id: data,
title: 'A mocked post',
})),
}))

test('the title of the post comes from fetchPost', async () => {
render(
<QueryClientProvider client={new QueryClient()}>
<PostTitle postId="42" />
</QueryClientProvider>,
)

expect(await screen.findByText('A mocked post')).toBeTruthy()
expect(fetchPost).toHaveBeenCalledWith({ data: '42' })
})
```

`importOriginal` loads the module as client code, so its server-only imports stay out of the test. A module mock only changes what other modules import: a call in the module that defines the server function still goes to the server function itself.

## Limits

- Vitest is the only supported test runner.
- The route tree is not regenerated while Vitest watches.
1 change: 1 addition & 0 deletions e2e/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@
- For new browser tests, reuse the local error-checking fixture. The shared `test` from `@tanstack/router-e2e-utils` fails on unexpected `console.error`, including hydration errors; allow only expected errors with `whitelistErrors`.
- HMR/watch tests edit real app sources. Reuse existing edit/restore helpers such as `createHmrFileEditor`, restore edits in teardown even after failures, and preserve the suites' single-worker and Nx `parallelism: false` settings.
- `@tanstack/router-e2e-utils:test:unit` is a placeholder. Validate helper changes through consuming e2e projects.
- An e2e project resolves `@tanstack/*` to links into `packages/*`, which Vite and Vitest treat as source code: always compiled, never externalized. A user has them in `node_modules`. For changes to what our plugins tell a bundler or a test runner about dependencies (`resolve.noExternal`, `resolve.external`, `optimizeDeps`, inline lists), run the project as a user's project too with [`scripts/e2e/run-as-installed.mjs`](../scripts/e2e/run-as-installed.md); `e2e/react-start/vitest-*` do so in `test:e2e`.
7 changes: 7 additions & 0 deletions e2e/react-start/vitest-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
node_modules
.DS_Store
dist
.output
.tanstack
*.local
__screenshots__
45 changes: 45 additions & 0 deletions e2e/react-start/vitest-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
{
"name": "tanstack-react-start-e2e-vitest-app",
"private": true,
"sideEffects": false,
"type": "module",
"scripts": {
"test:e2e": "pnpm run test:e2e:types && pnpm run test:e2e:linked && pnpm run test:e2e:cached && pnpm run test:e2e:installed",
"test:e2e:types": "tsc --noEmit",
"test:e2e:linked": "vitest --clearCache && vitest run",
"test:e2e:cached": "vitest run",
"test:e2e:installed": "node ../../../scripts/e2e/run-as-installed.mjs vitest run"
},
"dependencies": {
"@tanstack/react-router": "workspace:^",
"@tanstack/react-query": "catalog:",
"@tanstack/react-start": "workspace:^",
"react": "catalog:",
"react-dom": "catalog:"
},
"devDependencies": {
"@testing-library/react": "catalog:",
"@types/node": "^22.10.2",
"@types/react": "catalog:",
"@types/react-dom": "catalog:",
"@vitejs/plugin-react": "catalog:",
"@vitest/browser-playwright": "5.1.1",
"jsdom": "catalog:",
"playwright": "^1.63.0",
"typescript": "npm:@typescript/typescript6@^6.0.2",
"vite": "catalog:",
"vitest": "catalog:"
},
"nx": {
"targets": {
"test:e2e": {
"inputs": [
"buildProduction",
"^production",
"dependentTaskOutputs",
"{workspaceRoot}/scripts/e2e/run-as-installed.mjs"
]
}
}
}
}
8 changes: 8 additions & 0 deletions e2e/react-start/vitest-app/src/components/PostTitle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { useQuery } from '@tanstack/react-query'
import { postQueryOptions } from '../post-query-options'

export function PostTitle({ postId }: { postId: string }) {
const { data: post } = useQuery(postQueryOptions(postId))

return <h1>{post ? post.title : 'Loading...'}</h1>
}
25 changes: 25 additions & 0 deletions e2e/react-start/vitest-app/src/embedded/root.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Outlet, createRootRoute } from '@tanstack/react-router'
import { readSecret } from '../server-only'

// The root of a second route tree that is built by hand, for a part of the
// app that is embedded elsewhere. It is not in the routes directory, so the
// route generator never sees this module.
export const Route = createRootRoute({
// Only the server uses the three options below.
server: {
handlers: {
GET: () => new Response(readSecret()),
},
},
headers: () => ({ 'x-secret-length': String(readSecret().length) }),
ssr: 'data-only',
component: EmbeddedRoot,
})

function EmbeddedRoot() {
return (
<main>
<Outlet />
</main>
)
}
8 changes: 8 additions & 0 deletions e2e/react-start/vitest-app/src/post-query-options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { queryOptions } from '@tanstack/react-query'
import { fetchPost } from './posts'

export const postQueryOptions = (postId: string) =>
queryOptions({
queryKey: ['post', postId],
queryFn: () => fetchPost({ data: postId }),
})
17 changes: 17 additions & 0 deletions e2e/react-start/vitest-app/src/posts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { notFound } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import { addLike, findPost } from './server-only'

export const fetchPost = createServerFn()
.validator((postId: string) => postId)
.handler(({ data }) => {
const post = findPost(data)
if (!post) {
throw notFound()
}
return post
})

export const likePost = createServerFn({ method: 'POST' })
.validator((postId: string) => postId)
.handler(({ data }) => addLike(data))
104 changes: 104 additions & 0 deletions e2e/react-start/vitest-app/src/routeTree.gen.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/* eslint-disable */

// @ts-nocheck

// noinspection JSUnusedGlobalSymbols

// This file was automatically generated by TanStack Router.
// You should NOT make any changes in this file as it will be overwritten.
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.

import { Route as rootRouteImport } from './routes/__root'
import { Route as IndexRouteImport } from './routes/index'
import { Route as ApiHealthRouteImport } from './routes/api/health'
import { Route as PostsPostIdRouteImport } from './routes/posts.$postId'

const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
getParentRoute: () => rootRouteImport,
} as any)
const ApiHealthRoute = ApiHealthRouteImport.update({
id: '/api/health',
path: '/api/health',
getParentRoute: () => rootRouteImport,
} as any)
const PostsPostIdRoute = PostsPostIdRouteImport.update({
id: '/posts/$postId',
path: '/posts/$postId',
getParentRoute: () => rootRouteImport,
} as any)

export interface FileRoutesByFullPath {
'/': typeof IndexRoute
'/api/health': typeof ApiHealthRoute
'/posts/$postId': typeof PostsPostIdRoute
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
'/api/health': typeof ApiHealthRoute
'/posts/$postId': typeof PostsPostIdRoute
}
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
'/api/health': typeof ApiHealthRoute
'/posts/$postId': typeof PostsPostIdRoute
}
export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths: '/' | '/api/health' | '/posts/$postId'
fileRoutesByTo: FileRoutesByTo
to: '/' | '/api/health' | '/posts/$postId'
id: '__root__' | '/' | '/api/health' | '/posts/$postId'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
ApiHealthRoute: typeof ApiHealthRoute
PostsPostIdRoute: typeof PostsPostIdRoute
}

declare module '@tanstack/react-router' {
interface FileRoutesByPath {
'/': {
id: '/'
path: '/'
fullPath: '/'
preLoaderRoute: typeof IndexRouteImport
parentRoute: typeof rootRouteImport
}
'/api/health': {
id: '/api/health'
path: '/api/health'
fullPath: '/api/health'
preLoaderRoute: typeof ApiHealthRouteImport
parentRoute: typeof rootRouteImport
}
'/posts/$postId': {
id: '/posts/$postId'
path: '/posts/$postId'
fullPath: '/posts/$postId'
preLoaderRoute: typeof PostsPostIdRouteImport
parentRoute: typeof rootRouteImport
}
}
}

const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
ApiHealthRoute: ApiHealthRoute,
PostsPostIdRoute: PostsPostIdRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
._addFileTypes<FileRouteTypes>()

import type { getRouter } from './router.tsx'
import type { createStart } from '@tanstack/react-start'
declare module '@tanstack/react-start' {
interface Register {
ssr: true
router: Awaited<ReturnType<typeof getRouter>>
}
}
6 changes: 6 additions & 0 deletions e2e/react-start/vitest-app/src/router.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'

export function getRouter() {
return createRouter({ routeTree })
}
Loading
Loading