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
26 changes: 26 additions & 0 deletions .changeset/start-mock-server-fn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'@tanstack/start-client-core': minor
'@tanstack/react-start': minor
'@tanstack/solid-start': minor
'@tanstack/vue-start': minor
'@tanstack/start-plugin-core': minor
---

Add `mockServerFn` and `resetServerFnMocks` for client tests, exported from `@tanstack/react-start/testing`, `@tanstack/solid-start/testing` and `@tanstack/vue-start/testing`. Experimental.

A client test has no server. When Vitest compiles a project with Start's plugin, a server function call in client code no longer sends a request. It goes to the mock a test registered for that function, and fails with an error that names the function when there is none.

```ts
import { mockServerFn } from '@tanstack/react-start/testing'

test('greets', async () => {
mockServerFn(greet, ({ data }) => `Hello ${data}`)
// ...
})
```

A mock that a test registers ends with that test. Start's plugin adds a setup file to every Vitest project for this. `resetServerFnMocks` removes mocks earlier.

Concurrent tests keep their mocks apart. In jsdom, happy-dom and Node, each test runs in its own async context, so a call gets the mock of the test that made it. In browser mode, the `mockServerFn` and `resetServerFnMocks` of the test context (`({ mockServerFn }) =>`) tie a mock to its test, so it ends with that test; when concurrent tests there mock the same server function, the mock registered last answers the calls of both.

The mock is typed from the server function: it gets the `data` the function is called with, and has to return what the function's handler returns. It stands for the server side of the function (its server middleware, validator and handler); the function's client middleware runs as in the app. Unlike a module mock, it also answers a call made in the file that defines the server function.
5 changes: 5 additions & 0 deletions .changeset/start-server-middleware-signal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/start-client-core': patch
---

The options of a function middleware's server function no longer declare `signal`. Start never set it there, so code that read it got `undefined`. The signal of the request is `getRequest().signal`.
37 changes: 37 additions & 0 deletions .changeset/start-server-test-harness.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
'@tanstack/start-server-core': minor
'@tanstack/start-client-core': minor
'@tanstack/start-plugin-core': minor
'@tanstack/start-storage-context': patch
'@tanstack/react-start': minor
'@tanstack/solid-start': minor
'@tanstack/vue-start': minor
---

Add `runInRequest`, `mockMiddleware` and `runMiddleware` for server tests, exported from `@tanstack/react-start/testing/server`, `@tanstack/solid-start/testing/server` and `@tanstack/vue-start/testing/server`. Experimental.

```ts
import {
mockMiddleware,
runInRequest,
runMiddleware,
} from '@tanstack/react-start/testing/server'

test('likePost counts a like', async () => {
await runInRequest({ headers: { cookie: 'session=ada' } }, async () => {
expect(await likePost({ data: '1' })).toBe(1)
expect(getResponseHeader('cache-control')).toBe('no-store')
})
})
```

- `runInRequest` runs a callback as the code that handles one request. The request middleware of `src/start.ts` runs first. A server function call inside the callback runs as a loader's call does during server rendering: its middleware, its validator and its handler. Start's request and response helpers work inside the callback. `globalMiddleware: 'skip'` leaves the middleware of `src/start.ts` out and takes a `context` that is typed from the start instance.
- `mockMiddleware` replaces a middleware with a function that is typed from it. A mock ends with the test that registered it, or with the request when it was registered inside `runInRequest`.
- `runMiddleware` calls the server function of one middleware, for a function middleware and for a request middleware.

A server function that a test calls outside of `runInRequest` fails with an error that names `runInRequest`.

Fixes for test runs:

- A server test could not call a server function when Vitest served the calling module from its module cache, which is the default from the second run on. The call failed with "Invalid server function ID". In a test run the server now finds a function by its id alone.
- A project without a router entry could not load `@tanstack/react-start/server` in a server test (`Missing "#tanstack-router-entry" specifier`).
481 changes: 460 additions & 21 deletions docs/start/framework/react/guide/testing.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion e2e/react-start/vitest-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
"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:types": "node ../../../scripts/e2e/run-as-installed.mjs tsc6 --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"
Expand Down
12 changes: 12 additions & 0 deletions e2e/react-start/vitest-app/src/components/LikeButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useState } from 'react'
import { likePost } from '../posts'

export function LikeButton({ postId }: { postId: string }) {
const [likes, setLikes] = useState<number>()

return (
<button onClick={async () => setLikes(await likePost({ data: postId }))}>
{likes === undefined ? 'Like' : `${likes} likes`}
</button>
)
}
13 changes: 13 additions & 0 deletions e2e/react-start/vitest-app/src/middleware/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { createMiddleware } from '@tanstack/react-start'
import { getCookie } from '@tanstack/react-start/server'
import { findUserBySession } from '../server-only'

export const authMiddleware = createMiddleware({ type: 'function' }).server(
({ next }) => {
const user = findUserBySession(getCookie('session'))
if (!user) {
throw new Error('Not signed in')
}
return next({ context: { user } })
},
)
16 changes: 12 additions & 4 deletions e2e/react-start/vitest-app/src/posts.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import { notFound } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import { addLike, findPost } from './server-only'
import { setResponseHeader } from '@tanstack/react-start/server'
import { authMiddleware } from './middleware/auth'
import { addLike, countPosts, findPost } from './server-only'

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

export const fetchPostCount = createServerFn().handler(() => countPosts())

export const likePost = createServerFn({ method: 'POST' })
.middleware([authMiddleware])
.validator((postId: string) => postId)
.handler(({ data }) => addLike(data))
.handler(({ data, context }) => {
setResponseHeader('cache-control', 'no-store')
return addLike(data, context.user.id)
})
3 changes: 2 additions & 1 deletion e2e/react-start/vitest-app/src/routeTree.gen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,11 @@ export const routeTree = rootRouteImport
._addFileTypes<FileRouteTypes>()

import type { getRouter } from './router.tsx'
import type { createStart } from '@tanstack/react-start'
import type { startInstance } from './start.ts'
declare module '@tanstack/react-start' {
interface Register {
ssr: true
router: Awaited<ReturnType<typeof getRouter>>
config: Awaited<ReturnType<typeof startInstance.getOptions>>
}
}
49 changes: 40 additions & 9 deletions e2e/react-start/vitest-app/src/server-only.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,53 @@ export function readSecret() {
return 'the server secret'
}

export type Locale = 'en' | 'de'

export interface Post {
id: string
title: string
}

const posts = new Map<string, Post>([
['1', { id: '1', title: 'The first post' }],
export interface User {
id: string
name: string
}

const posts = new Map<string, Record<Locale, string>>([
['1', { en: 'The first post', de: 'Der erste Beitrag' }],
['2', { en: 'The second post', de: 'Der zweite Beitrag' }],
['3', { en: 'The third post', de: 'Der dritte Beitrag' }],
])
const likes = new Map<string, number>()
const users = new Map<string, User>([['ada', { id: 'u1', name: 'Ada' }]])
const likes = new Map<string, Set<string>>()
const calls: Array<string> = []

export function countPosts(): number {
return posts.size
}

export function findPost(id: string, locale: Locale): Post | undefined {
const titles = posts.get(id)
return titles && { id, title: titles[locale] }
}

/** The user of a session cookie. */
export function findUserBySession(session: string | undefined) {
return session ? users.get(session) : undefined
}

/** Counts each user once. Returns the number of likes of the post. */
export function addLike(postId: string, userId: string): number {
const users = likes.get(postId) ?? new Set()
likes.set(postId, users.add(userId))
return users.size
}

export function findPost(id: string): Post | undefined {
return posts.get(id)
/** The audit log of the app: the server functions that were called. */
export function recordCall(name: string) {
calls.push(name)
}

export function addLike(postId: string): number {
const count = (likes.get(postId) ?? 0) + 1
likes.set(postId, count)
return count
export function recordedCalls(): ReadonlyArray<string> {
return calls
}
27 changes: 27 additions & 0 deletions e2e/react-start/vitest-app/src/start.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { createMiddleware, createStart } from '@tanstack/react-start'
import { recordCall } from './server-only'
import type { Locale } from './server-only'

// The global middleware of the app. It is not exported, as in most apps.
// tests/posts.server.test.ts shows how a test runs it and how a test leaves
// it out.
const localeMiddleware = createMiddleware().server(({ next, request }) => {
const locale: Locale = request.headers
.get('accept-language')
?.startsWith('de')
? 'de'
: 'en'
return next({ context: { locale } })
})

const auditMiddleware = createMiddleware({ type: 'function' }).server(
({ next, serverFnMeta }) => {
recordCall(serverFnMeta.name)
return next()
},
)

export const startInstance = createStart(() => ({
requestMiddleware: [localeMiddleware],
functionMiddleware: [auditMiddleware],
}))
89 changes: 89 additions & 0 deletions e2e/react-start/vitest-app/tests/concurrent-mocks.client.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
// Mocks of `mockServerFn` in tests that run at the same time. The file runs in
// browser mode and in jsdom.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { cleanup, render, within } from '@testing-library/react'
import { mockServerFn } from '@tanstack/react-start/testing'
import { afterAll, expect, test } from 'vitest'
import { PostTitle } from '../src/components/PostTitle'
import { fetchPost, fetchPostCount, likePost } from '../src/posts'

// jsdom runs in Node, which has the async context that tells concurrent tests
// apart. Browser mode has none.
const hasAsyncContext =
typeof process !== 'undefined' && !!process.versions?.node

const later = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))

function renderPostTitle(postId: string) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
return render(
<QueryClientProvider client={queryClient}>
<PostTitle postId={postId} />
</QueryClientProvider>,
)
}

// (concurrent tests share one document: each one queries its own container)
afterAll(cleanup)

test.concurrent(
'a mock of the test context answers the calls of its test',
async ({ mockServerFn }) => {
mockServerFn(fetchPost, ({ data }) => ({ id: data, title: 'From test 1' }))
const view = renderPostTitle('1')

expect(await within(view.container).findByText('From test 1')).toBeTruthy()
},
)

// It starts before the next test, so without async context that test is the
// one that started last. The reset of the test context still removes only the
// mocks of its own test. (It mocks a server function that no other test of the
// file mocks: in browser mode another running test's mock of the same function
// would answer after the reset.)
test.concurrent(
'a reset of the test context removes the mocks of its test only',
async ({ mockServerFn, resetServerFnMocks }) => {
mockServerFn(fetchPostCount, () => 3)
await later(10)

resetServerFnMocks()

await expect(fetchPostCount()).rejects.toThrow('no server runs')
},
)

// The test above ends while this one waits. Only its own mocks went with it.
test.concurrent(
'a mock of the test context stays until its own test ends',
async ({ mockServerFn }) => {
mockServerFn(likePost, () => 7)
await later(50)

await expect(likePost({ data: '1' })).resolves.toBe(7)
},
)

for (const [name, delay] of [
['A', 20],
['B', 0],
] as const) {
test.skipIf(!hasAsyncContext)(
`concurrent tests that mock the same server function each get their own answer (${name})`,
{ concurrent: true },
async () => {
mockServerFn(fetchPost, ({ data }) => ({
id: data,
title: `Post ${name}`,
}))
await later(delay)
const view = renderPostTitle(name)

expect(
await within(view.container).findByText(`Post ${name}`),
).toBeTruthy()
},
)
}
21 changes: 21 additions & 0 deletions e2e/react-start/vitest-app/tests/like-button.client.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { mockServerFn } from '@tanstack/react-start/testing'
import { afterEach, expect, test, vi } from 'vitest'
import { LikeButton } from '../src/components/LikeButton'
import { likePost } from '../src/posts'

afterEach(() => {
cleanup()
})

test('a component sends its data to a server function and shows the answer', async () => {
const like = vi.fn(() => 5)
mockServerFn(likePost, like)
render(<LikeButton postId="42" />)

fireEvent.click(screen.getByRole('button', { name: 'Like' }))

expect(await screen.findByRole('button', { name: '5 likes' })).toBeDefined()
expect(like).toHaveBeenCalledOnce()
expect(like).toHaveBeenCalledWith(expect.objectContaining({ data: '42' }))
})
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @vitest-environment jsdom

// A test that replaces a server function with a module mock (`vi.mock`).
// Start's compiler must leave this working: the
// A test that replaces a server function with a module mock (`vi.mock`)
// instead of `mockServerFn`. Start's compiler must leave this working: the
// module the mock replaces, the original that `importOriginal` loads, and the
// module that imports the mocked function. The project runs its tests in Node
// by default, and this file switches to jsdom with the comment above.
Expand Down
Loading
Loading