From 63c17e8bd978ff8463e53c2de536d15a23469e58 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Thu, 19 Nov 2026 14:49:24 +0100 Subject: [PATCH] feat(start): typed test helpers for server functions and middleware Client tests: - `mockServerFn` and `resetServerFnMocks` (`-start/testing`). In a test run a server function call in client code sends no request: it goes to a mock that is typed from the function, and fails with an error that names the function when there is none. The mock also answers a call made in the file that defines the function. Server tests (`-start/testing/server`): - `runInRequest` runs a callback as the code that handles one request. The request middleware of `src/start.ts` runs first, through the app's own request middleware pipeline, which moves unchanged into `request-middleware.ts`. A server function call inside runs as a loader's call does during server rendering, and Start's request and response helpers work. `globalMiddleware: 'skip'` leaves the middleware of `src/start.ts` out and takes a `context` typed from the start instance. - `mockMiddleware` replaces a middleware with a function typed from it, its client function included. - `runMiddleware` calls the server function of one middleware. Mocks: - Each mock belongs to the test that registered it, or to the file, and ends with it. Start's plugin adds a setup file to every Vitest project. In Node, jsdom and happy-dom each test runs in its own async context, so concurrent tests keep their mocks apart. In browser mode the test context has `mockServerFn` and `resetServerFnMocks` bound to its test. - A mock registered after its test ended throws. Also: - In a test run the server finds a server function by its id alone: Vitest serves compiled modules from its cache, so the compiler has no record. - The options of a function middleware's server function no longer declare `signal`, which Start never set. The request's signal is `getRequest().signal`. - The "No Start context found" error names `runInRequest` in tests. - The e2e projects use every helper and type-check as installed. Co-Authored-By: Claude Opus 5.5 --- .changeset/start-mock-server-fn.md | 26 + .changeset/start-server-middleware-signal.md | 5 + .changeset/start-server-test-harness.md | 37 + docs/start/framework/react/guide/testing.md | 481 +++++++++- e2e/react-start/vitest-app/package.json | 2 +- .../vitest-app/src/components/LikeButton.tsx | 12 + .../vitest-app/src/middleware/auth.ts | 13 + e2e/react-start/vitest-app/src/posts.ts | 16 +- .../vitest-app/src/routeTree.gen.ts | 3 +- e2e/react-start/vitest-app/src/server-only.ts | 49 +- e2e/react-start/vitest-app/src/start.ts | 27 + .../tests/concurrent-mocks.client.test.tsx | 89 ++ .../tests/like-button.client.test.tsx | 21 + .../tests/module-mocks/post-title.test.tsx | 4 +- .../vitest-app/tests/posts.server.test.ts | 114 +++ .../tests/route-tree.client.test.tsx | 18 +- e2e/react-start/vitest-app/vite.config.ts | 5 +- e2e/react-start/vitest-library/package.json | 2 +- e2e/react-start/vitest-library/src/account.ts | 10 + .../vitest-library/src/greeting.ts | 24 + e2e/react-start/vitest-library/src/session.ts | 23 + e2e/react-start/vitest-library/src/tenant.ts | 15 + .../tests/account.server.test.ts | 97 ++ .../tests/greeting.client.test.ts | 39 + .../tests/greeting.server.test.ts | 50 ++ .../tests/tenant.server.test.ts | 30 + .../vitest-library/vitest.config.ts | 5 +- packages/react-start/package.json | 18 + packages/react-start/src/testing.ts | 10 + .../react-start/src/testing/client-rpc.ts | 1 + packages/react-start/src/testing/server.ts | 1 + packages/react-start/vite.config.ts | 3 + packages/solid-start/package.json | 18 + packages/solid-start/src/testing.ts | 10 + .../solid-start/src/testing/client-rpc.ts | 1 + packages/solid-start/src/testing/server.ts | 1 + packages/solid-start/vite.config.ts | 3 + packages/start-client-core/package.json | 26 + .../start-client-core/src/createMiddleware.ts | 1 - packages/start-client-core/src/index.tsx | 2 + .../src/testing/client-rpc.ts | 2 + .../src/testing/createClientRpc.ts | 24 + .../start-client-core/src/testing/index.ts | 8 + .../src/testing/mockStores.ts | 140 +++ .../src/testing/serverFnMocks.ts | 176 ++++ .../start-client-core/src/testing/vitest.ts | 35 + .../src/tests/serverFnMocks.test-d.ts | 58 ++ .../tests/mockStores.async-context.test.ts | 87 ++ .../tests/mockStores.test.ts | 112 +++ .../tests/serverFnMocks.test.ts | 192 ++++ packages/start-client-core/vite.config.ts | 3 + packages/start-plugin-core/AGENTS.md | 1 + packages/start-plugin-core/package.json | 1 + .../start-plugin-core/src/vite/planning.ts | 5 + packages/start-plugin-core/src/vite/plugin.ts | 8 +- .../src/vite/start-compiler-plugin/plugin.ts | 30 +- .../start-plugin-core/src/vite/test-run.ts | 40 + .../tests/integration/start-test-run.test.ts | 41 +- .../tests/vite/test-config-plan.test.ts | 18 + .../tests/vite/test-run.test.ts | 35 + packages/start-server-core/package.json | 6 + .../src/createStartHandler.ts | 411 +-------- .../src/request-middleware.ts | 427 +++++++++ .../start-server-core/src/testing/index.ts | 33 + .../src/testing/middlewareMocks.ts | 197 ++++ .../src/testing/runInRequest.ts | 295 ++++++ .../src/testing/runMiddleware.ts | 245 +++++ .../start-server-core/src/testing/scope.ts | 36 + .../start-server-core/src/testing/types.ts | 86 ++ .../start-server-core/tests/testing.test-d.ts | 207 +++++ .../start-server-core/tests/testing.test.ts | 849 ++++++++++++++++++ packages/start-server-core/vite.config.ts | 1 + .../src/async-local-storage.ts | 6 +- packages/vue-start/package.json | 18 + packages/vue-start/src/testing.ts | 10 + packages/vue-start/src/testing/client-rpc.ts | 1 + packages/vue-start/src/testing/server.ts | 1 + packages/vue-start/vite.config.ts | 3 + pnpm-lock.yaml | 30 +- scripts/e2e/run-as-installed.md | 8 + 80 files changed, 4707 insertions(+), 491 deletions(-) create mode 100644 .changeset/start-mock-server-fn.md create mode 100644 .changeset/start-server-middleware-signal.md create mode 100644 .changeset/start-server-test-harness.md create mode 100644 e2e/react-start/vitest-app/src/components/LikeButton.tsx create mode 100644 e2e/react-start/vitest-app/src/middleware/auth.ts create mode 100644 e2e/react-start/vitest-app/src/start.ts create mode 100644 e2e/react-start/vitest-app/tests/concurrent-mocks.client.test.tsx create mode 100644 e2e/react-start/vitest-app/tests/like-button.client.test.tsx create mode 100644 e2e/react-start/vitest-app/tests/posts.server.test.ts create mode 100644 e2e/react-start/vitest-library/src/account.ts create mode 100644 e2e/react-start/vitest-library/src/greeting.ts create mode 100644 e2e/react-start/vitest-library/src/session.ts create mode 100644 e2e/react-start/vitest-library/src/tenant.ts create mode 100644 e2e/react-start/vitest-library/tests/account.server.test.ts create mode 100644 e2e/react-start/vitest-library/tests/greeting.client.test.ts create mode 100644 e2e/react-start/vitest-library/tests/greeting.server.test.ts create mode 100644 e2e/react-start/vitest-library/tests/tenant.server.test.ts create mode 100644 packages/react-start/src/testing.ts create mode 100644 packages/react-start/src/testing/client-rpc.ts create mode 100644 packages/react-start/src/testing/server.ts create mode 100644 packages/solid-start/src/testing.ts create mode 100644 packages/solid-start/src/testing/client-rpc.ts create mode 100644 packages/solid-start/src/testing/server.ts create mode 100644 packages/start-client-core/src/testing/client-rpc.ts create mode 100644 packages/start-client-core/src/testing/createClientRpc.ts create mode 100644 packages/start-client-core/src/testing/index.ts create mode 100644 packages/start-client-core/src/testing/mockStores.ts create mode 100644 packages/start-client-core/src/testing/serverFnMocks.ts create mode 100644 packages/start-client-core/src/testing/vitest.ts create mode 100644 packages/start-client-core/src/tests/serverFnMocks.test-d.ts create mode 100644 packages/start-client-core/tests/mockStores.async-context.test.ts create mode 100644 packages/start-client-core/tests/mockStores.test.ts create mode 100644 packages/start-client-core/tests/serverFnMocks.test.ts create mode 100644 packages/start-server-core/src/request-middleware.ts create mode 100644 packages/start-server-core/src/testing/index.ts create mode 100644 packages/start-server-core/src/testing/middlewareMocks.ts create mode 100644 packages/start-server-core/src/testing/runInRequest.ts create mode 100644 packages/start-server-core/src/testing/runMiddleware.ts create mode 100644 packages/start-server-core/src/testing/scope.ts create mode 100644 packages/start-server-core/src/testing/types.ts create mode 100644 packages/start-server-core/tests/testing.test-d.ts create mode 100644 packages/start-server-core/tests/testing.test.ts create mode 100644 packages/vue-start/src/testing.ts create mode 100644 packages/vue-start/src/testing/client-rpc.ts create mode 100644 packages/vue-start/src/testing/server.ts diff --git a/.changeset/start-mock-server-fn.md b/.changeset/start-mock-server-fn.md new file mode 100644 index 00000000000..223bdae7bd7 --- /dev/null +++ b/.changeset/start-mock-server-fn.md @@ -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. diff --git a/.changeset/start-server-middleware-signal.md b/.changeset/start-server-middleware-signal.md new file mode 100644 index 00000000000..39fa82c2ff4 --- /dev/null +++ b/.changeset/start-server-middleware-signal.md @@ -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`. diff --git a/.changeset/start-server-test-harness.md b/.changeset/start-server-test-harness.md new file mode 100644 index 00000000000..a1226bd5c8c --- /dev/null +++ b/.changeset/start-server-test-harness.md @@ -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`). diff --git a/docs/start/framework/react/guide/testing.md b/docs/start/framework/react/guide/testing.md index 9d1b2bebeb0..a70ec3c77c3 100644 --- a/docs/start/framework/react/guide/testing.md +++ b/docs/start/framework/react/guide/testing.md @@ -9,7 +9,7 @@ Start's Vite plugin compiles your code for the environment it runs in. In client 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. +The examples on this page use React. `@tanstack/solid-start` and `@tanstack/vue-start` export the same functions from the same subpaths. ## Setup @@ -88,40 +88,479 @@ A test run never writes to your route files. The dev server fills in an empty ro 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 +## Mocking 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: +A client test has no server. When client code calls a server function in a test run, no request is sent. The call goes to a mock that the test registered for that function with `mockServerFn`. -```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' +Take a route whose loader gets a post from a server function: + +```ts title="src/posts.ts" +import { notFound } from '@tanstack/react-router' +import { createServerFn } from '@tanstack/react-start' +import { findPost } from './db.server' + +export const fetchPost = createServerFn() + .validator((postId: string) => postId) + .handler(async ({ data }) => { + const post = await findPost(data) + if (!post) { + throw notFound() + } + return post + }) +``` + +```tsx title="src/routes/posts.$postId.tsx" +import { createFileRoute } from '@tanstack/react-router' +import { fetchPost } from '../posts' + +export const Route = createFileRoute('/posts/$postId')({ + loader: ({ params }) => fetchPost({ data: params.postId }), + component: PostPage, +}) + +function PostPage() { + const post = Route.useLoaderData() + + return

{post.title}

+} +``` + +The test renders the route. The mock answers the loader's call in place of the server: + +```tsx title="tests/post-page.client.test.tsx" +import { cleanup, render, screen } from '@testing-library/react' +import { + RouterProvider, + createMemoryHistory, + createRouter, +} from '@tanstack/react-router' +import { mockServerFn } from '@tanstack/react-start/testing' +import { afterEach, expect, test } from 'vitest' import { fetchPost } from '../src/posts' +import { routeTree } from '../src/routeTree.gen' + +afterEach(() => { + cleanup() +}) -vi.mock('../src/posts', async (importOriginal) => ({ - ...(await importOriginal()), - fetchPost: vi.fn(async ({ data }: { data: string }) => ({ +test('the post page shows the title of the post', async () => { + mockServerFn(fetchPost, ({ data }) => ({ id: data, - title: 'A mocked post', - })), + title: 'Testing with TanStack Start', + })) + const router = createRouter({ + routeTree, + history: createMemoryHistory({ initialEntries: ['/posts/42'] }), + }) + + render() + + expect((await screen.findByRole('heading')).textContent).toBe( + 'Testing with TanStack Start', + ) +}) +``` + +The mock stands for the server side of the function: its server middleware, its validator and its handler. It is called where the app would send the request, so the function's client middleware runs as in the app, before the mock and after it. + +A mock also answers a call that is made in the module that defines the server function. A module mock (`vi.mock`) cannot replace such a call, because it only changes what other modules import. + +A call to a server function that has no mock fails with an error that names the function: + +``` +The server function "fetchPost" (/src/posts.ts) was called in a client test, where no server runs. Answer the call with mockServerFn() before it is made. +``` + +### `mockServerFn(serverFn, mock)` + +Registers `mock` as the answer to every call of `serverFn`. A mock that a test registers ends with that test, see [How long a mock lasts](#how-long-a-mock-lasts). A second call for the same function in the same test replaces the first mock, and a mock of the test takes precedence over one of the file. + +The test context has a `mockServerFn` and a `resetServerFnMocks` too: `test('...', ({ mockServerFn, resetServerFnMocks }) => { ... })`. They do the same and belong to that test in every environment, which matters for [tests that run concurrently](#tests-that-run-concurrently) in browser mode. TypeScript knows it once a file of the project imports from `@tanstack/react-start/testing`; a project that only uses the context's version adds `import type {} from '@tanstack/react-start/testing'` to a file its tests include. + +`mock` is typed from the server function. It gets one object: + +| Property | Type | Value | +| --------- | -------------------------- | ------------------------------------------------------------------------------ | +| `data` | The function's input | The `data` of the call, as the caller passed it. The validator has not run. | +| `method` | `'GET' \| 'POST'` | The method of the server function. | +| `headers` | `Headers` | The headers of the call, with the ones the function's client middleware added. | +| `signal` | `AbortSignal \| undefined` | The signal of the call. | + +`mock` returns what the call resolves to, or a promise for it. The return type is the handler's return type, literal types included: a mock of a handler that returns `{ status: 'ok' }` has to return exactly that. The value reaches the caller as it is. It is not passed through the serializer, so the test does not notice a value that the server could not send, such as a function. + +What `mock` throws rejects the call. To test how your code handles a redirect or a failed call, throw `redirect(...)` or an error in the mock. + +To check how a server function was called, pass a mock function of your test runner. Take a button that likes a post. `likePost` is a server function that takes the id of a post and returns its new number of likes: + +```tsx title="src/components/LikeButton.tsx" +import { useState } from 'react' +import { likePost } from '../posts' + +export function LikeButton({ postId }: { postId: string }) { + const [likes, setLikes] = useState() + + return ( + + ) +} +``` + +```tsx title="tests/like-button.client.test.tsx" +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('likes the post and shows the new count', async () => { + const like = vi.fn(() => 5) + mockServerFn(likePost, like) + render() + + fireEvent.click(screen.getByRole('button', { name: 'Like' })) + + expect(await screen.findByRole('button', { name: '5 likes' })).toBeDefined() + expect(like).toHaveBeenCalledWith(expect.objectContaining({ data: '42' })) +}) +``` + +`mockServerFn` works in client tests only. In a server test it throws, because the function was not compiled for the client. A server test runs the function itself, as the next section shows. + +### `resetServerFnMocks()` + +Removes the mocks that `mockServerFn` registered: the ones of the running test when it is called in a test, the ones of the file otherwise. Start ends the mocks of a test when the test ends, so most tests never call it. + +## Testing server functions and middleware in server tests + +In a server test your code runs as it does on the server, and a server function runs in full: its middleware, its validator and its handler. The helpers for server tests come from `@tanstack/react-start/testing/server`. + +### Calling a server function + +On the server, a server function runs for a request. It reads the cookies of that request, sets headers on the response, and gets context from the middleware that ran before it. A server function that a test calls outside of a request fails: + +``` +No Start context found in AsyncLocalStorage. Make sure you are using the function within the server runtime. In a test, run this code inside runInRequest(), which the testing/server entry of your Start package exports (for example '@tanstack/react-start/testing/server'). +``` + +`runInRequest` runs a callback as the code that handles one request to your server. Take `fetchPost` and `likePost` from above. `likePost` uses a middleware that finds the user of the session cookie: + +```ts title="src/middleware/auth.ts" +import { createMiddleware } from '@tanstack/react-start' +import { getCookie } from '@tanstack/react-start/server' +import { findUserBySession } from '../db.server' + +export const authMiddleware = createMiddleware({ type: 'function' }).server( + async ({ next }) => { + const user = await findUserBySession(getCookie('session')) + if (!user) { + throw new Error('Not signed in') + } + return next({ context: { user } }) + }, +) +``` + +```ts title="src/posts.ts" +import { createServerFn } from '@tanstack/react-start' +import { setResponseHeader } from '@tanstack/react-start/server' +import { addLike } from './db.server' +import { authMiddleware } from './middleware/auth' + +export const likePost = createServerFn({ method: 'POST' }) + .middleware([authMiddleware]) + .validator((postId: string) => postId) + .handler(async ({ data, context }) => { + setResponseHeader('cache-control', 'no-store') + // Counts each user once and returns the number of likes. + return addLike(data, context.user.id) + }) +``` + +```ts title="tests/posts.server.test.ts" +import { getResponseHeader } from '@tanstack/react-start/server' +import { runInRequest } from '@tanstack/react-start/testing/server' +import { expect, test } from 'vitest' +import { fetchPost, likePost } from '../src/posts' + +test('fetchPost returns the post', async () => { + const post = await runInRequest(() => fetchPost({ data: '1' })) + + expect(post.title).toBe('The first post') +}) + +test('fetchPost fails for a post that does not exist', async () => { + await expect( + runInRequest(() => fetchPost({ data: 'unknown' })), + ).rejects.toMatchObject({ isNotFound: true }) +}) + +test('likePost counts a user once', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + expect(await likePost({ data: '1' })).toBe(1) + expect(await likePost({ data: '1' })).toBe(1) + + expect(getResponseHeader('cache-control')).toBe('no-store') + }) +}) + +test('likePost refuses a request without a session', async () => { + await expect(runInRequest(() => likePost({ data: '1' }))).rejects.toThrow( + 'Not signed in', + ) +}) +``` + +The handlers in these tests use the real `./db.server`. A server test loads your server code as it is, so the test has to provide the data that code reads, for example a test database with a post `1` and a session `ada`. + +Each server function call inside the callback runs like a call that a loader makes while the server renders a page. The middleware of the function runs, client functions first and server functions after them, then the validator and the handler. The data and the result are passed as they are and do not go through the serializer. + +Start's request and response helpers work inside the callback: `getRequest`, `getCookie`, `setResponseHeader`, `getResponseHeader` and the other functions of `@tanstack/react-start/server`. A test can call several server functions in one request and check the response between the calls, as the third test does. + +### `runInRequest(options, callback)` + +Runs `callback` for one request. It resolves to what the callback returns and rejects with what the callback throws. `options` can be left out: `runInRequest(callback)`. + +| Option | Type | Value | +| ------------------ | -------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| `url` | `string \| URL` | The URL of the request. A relative URL is resolved against `http://localhost`. The default is `/`. | +| `method` | `string` | The method of the request. The default is `GET`. | +| `headers` | `HeadersInit` | The headers of the request. Cookies go into the `cookie` header. | +| `request` | `Request` | A request that is used as it is. It takes the place of `url`, `method` and `headers`. | +| `context` | Your request context | The context your server entry passes to Start with a request. It is required when your app registers a request context. | +| `globalMiddleware` | `'skip'` | Leaves out the middleware of `src/start.ts`. [Global middleware](#global-middleware) describes it. | + +The request counts as a request for a page. Request middleware gets `handlerType: 'router'`, so a middleware that only acts on server function requests lets it through. The CSRF middleware in its usual setup is one of them. + +`getRouterInstance()` returns the router of your router entry, at the URL of the request. + +### Global middleware + +`runInRequest` runs the request middleware of `src/start.ts` before the callback, and the function middleware of `src/start.ts` with each server function call. Take an app whose request middleware reads the language of the request: + +```ts title="src/start.ts" +import { createMiddleware, createStart } from '@tanstack/react-start' + +type Locale = 'en' | 'de' + +const localeMiddleware = createMiddleware().server(({ next, request }) => { + const locale: Locale = request.headers + .get('accept-language') + ?.startsWith('de') + ? 'de' + : 'en' + return next({ context: { locale } }) +}) + +export const startInstance = createStart(() => ({ + requestMiddleware: [localeMiddleware], })) +``` -test('the title of the post comes from fetchPost', async () => { - render( - - - , +If the handler of `fetchPost` looks the post up with `findPost(data, context.locale)`, a test chooses the language with a header: + +```ts +test('fetchPost returns the post in the language of the request', async () => { + const post = await runInRequest( + { headers: { 'accept-language': 'de-DE' } }, + () => fetchPost({ data: '1' }), + ) + + expect(post.title).toBe('Der erste Beitrag') +}) +``` + +When a request middleware answers the request itself or throws, the callback does not run and `runInRequest` rejects. It rejects with what the middleware threw, or with an error that has the middleware's response as its `cause`. + +To keep the global middleware out of a test, pass `globalMiddleware: 'skip'`. Neither list of `src/start.ts` runs then. `context` takes the place of the context the two lists pass on: + +```ts +test('fetchPost returns the English post', async () => { + const post = await runInRequest( + { globalMiddleware: 'skip', context: { locale: 'en' } }, + () => fetchPost({ data: '1' }), + ) + + expect(post.title).toBe('The first post') +}) +``` + +The type of `context` comes from your start instance. TypeScript reports a missing property and a value the middleware could not have produced, such as `locale: 'fr'` here. The option needs no reference to a middleware, so it also works for middleware that `src/start.ts` does not export. A server function that lists one of the global middleware itself still runs it. + +### `mockMiddleware(middleware, mock)` + +Replaces a middleware in server tests. `likePost` needs a session, and the test below puts a user in its place: + +```ts title="tests/posts.server.test.ts" +import { + mockMiddleware, + runInRequest, +} from '@tanstack/react-start/testing/server' +import { expect, test } from 'vitest' +import { authMiddleware } from '../src/middleware/auth' +import { likePost } from '../src/posts' + +test('likePost counts the like of a user', async () => { + mockMiddleware(authMiddleware, ({ next }) => + next({ context: { user: { id: 'u2', name: 'Grace' } } }), ) - expect(await screen.findByText('A mocked post')).toBeTruthy() - expect(fetchPost).toHaveBeenCalledWith({ data: '42' }) + await expect(runInRequest(() => likePost({ data: '2' }))).resolves.toBe(1) +}) +``` + +`mock` stands for the server function of the middleware and is typed from it. It gets what that function gets: `data`, `context`, `method`, `serverFnMeta` and `next` for a function middleware, and `request`, `pathname`, `context`, `handlerType` and `next` for a request middleware. The signal of the request is `getRequest().signal`, as in the middleware. + +A mock goes on with the call by returning `next()`. When the middleware passes context on, `next` requires that context, because the code after the middleware reads it. A mock can also end the call the way the middleware can: by throwing, or by returning a `Response` in the mock of a request middleware. + +While a middleware is mocked, its client function does not run either. A server test would otherwise run that function in Node, where code written for a browser can fail. So the `context` of the mock has nothing that this client function sends to the server, and TypeScript leaves it out of the type. + +A mock registered inside the callback of `runInRequest` belongs to that request. It takes precedence over a mock of the test, and it ends with the request. If nothing in the request ran it, `runInRequest` rejects, because a mock that never runs usually means the test does not exercise what it was written for. + +The request middleware of `src/start.ts` has already run when the callback starts. Mock one of them before you call `runInRequest`. + +`mockMiddleware` replaces one middleware object. On the server, Start loads the file of a server function a second time, for the server side of the function. A middleware that is created in that file therefore exists twice, and a mock reaches only one of the two. Create a middleware that tests replace in a file of its own, like `src/middleware/auth.ts` above. + +### `runMiddleware(middleware, input, next)` + +Calls the server function of one middleware and nothing else. The middleware that it lists itself does not run, and neither does its validator or its client function. Call it inside `runInRequest`, which provides the request. + +```ts title="tests/auth.server.test.ts" +import { + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' +import { expect, test } from 'vitest' +import { authMiddleware } from '../src/middleware/auth' + +test('authMiddleware passes the user of the session on', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + const { context } = await runMiddleware(authMiddleware, {}) + + expect(context.user).toEqual({ id: 'u1', name: 'Ada' }) + }) +}) + +test('authMiddleware refuses a request without a session', async () => { + await runInRequest(async () => { + await expect(runMiddleware(authMiddleware, {})).rejects.toThrow( + 'Not signed in', + ) + }) +}) +``` + +`input` is what the server function of the middleware receives. Its type comes from the middleware. + +| Property | For | Value | +| -------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------ | +| `data` | Function middleware | The validated data. It is required when the middleware or a middleware it lists has a validator. | +| `context` | Both | The context of the middleware that runs before this one. It is required when that context has a required property. | +| `method` | Function middleware | The method of the server function. The default is `GET`. | +| `handlerType` | Request middleware | `'router'` for a page request, `'serverFn'` for a server function request. The default is `'router'`. | +| `serverFnMeta` | Both | The id, the name and the file of the server function that the call is for. | + +`next` is optional. It stands for everything that runs after the middleware, and it gets what the middleware passed on. For a function middleware it gets `context` and `sendContext`, and what it returns is the result of the call. For a request middleware it gets `context`, `request` and `pathname`, and it returns the `Response` of the request. Without it, the response is an empty one with status 200. + +`runMiddleware` resolves to an object: + +| Property | For | Value | +| ------------- | ------------------- | ----------------------------------------------------------------------------------------------- | +| `context` | Both | The context after the middleware: what it received and what it added. | +| `sendContext` | Function middleware | The context the middleware sends back to the client. | +| `result` | Function middleware | What `next` returned. | +| `response` | Request middleware | The response the middleware answers the request with: its own, or the one that `next` returned. | + +A request middleware often changes the response of the request. Take a middleware that derives a tenant from the host name: + +```ts title="src/middleware/tenant.ts" +import { createMiddleware } from '@tanstack/react-start' + +export const tenantMiddleware = createMiddleware().server( + async ({ next, request }) => { + const tenant = new URL(request.url).hostname.split('.')[0]! + if (tenant === 'www') { + return new Response('No tenant', { status: 404 }) + } + const result = await next({ context: { tenant } }) + result.response.headers.set('x-tenant', tenant) + return result + }, +) +``` + +```ts title="tests/tenant.server.test.ts" +import { + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' +import { expect, test, vi } from 'vitest' +import { tenantMiddleware } from '../src/middleware/tenant' + +test('tenantMiddleware names the tenant in the context and in a header', async () => { + await runInRequest({ url: 'https://acme.example.com/posts' }, async () => { + const { context, response } = await runMiddleware( + tenantMiddleware, + {}, + ({ context }) => new Response(`Posts of ${context.tenant}`), + ) + + expect(context).toEqual({ tenant: 'acme' }) + expect(response.headers.get('x-tenant')).toBe('acme') + await expect(response.text()).resolves.toBe('Posts of acme') + }) +}) + +test('tenantMiddleware answers a request without a tenant itself', async () => { + await runInRequest({ url: 'https://www.example.com/posts' }, async () => { + const next = vi.fn() + const { response } = await runMiddleware(tenantMiddleware, {}, next) + + expect(response.status).toBe(404) + expect(next).not.toHaveBeenCalled() + }) }) ``` -`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. +A `Response` that a request middleware throws counts as its answer, as in the app, so `response` holds it. What a function middleware throws rejects the call. + +If `tenantMiddleware` is listed in `src/start.ts`, `runInRequest` also runs it for the request of the test, before the callback. For the second test that run would end the request. Such a test passes `globalMiddleware: 'skip'`. + +`runMiddleware` calls the real server function of a middleware, also while `mockMiddleware` replaces that middleware. + +## How long a mock lasts + +Start's plugin adds a setup file to every Vitest project. The file ends a mock of `mockServerFn` or `mockMiddleware` together with the test that registered it: + +- A mock registered in a test, or in a `beforeEach` hook, lasts until that test ends. +- A mock registered at the top of a test file, or in a `beforeAll` hook, lasts for the whole file. +- A mock registered with `mockMiddleware` inside the callback of `runInRequest` lasts until that request ends. + +### Tests that run concurrently + +Tests in one file that run at the same time (`test.concurrent`) keep their mocks apart. When one of them ends, only its own mocks end. + +Which mock answers a call depends on whether the test environment can tell the tests apart while code runs: + +- In jsdom, happy-dom and Node, Start runs each test in its own async context. A call that code of a test makes gets the mock of that test, also when other tests mock the same function in a different way. +- In browser mode there is no async context. Register and reset mocks through the test context there: `test.concurrent('...', async ({ mockServerFn, resetServerFnMocks }) => { ... })`. A mock then ends with its own test, and a reset removes only the mocks of its own test. When two concurrent tests mock the same server function, the mock registered last answers the calls of both. Put such tests in separate files, which Vitest keeps apart, or let them run one after another. + +Work that a test starts and does not wait for can register a mock after the test has ended. That throws an error that says so: wait inside the test for that work. + +Code that runs for a test but was started outside it loses the test's context: an event that another test dispatches, for example. Concurrent tests also share one `document` in jsdom, so each test should query only the elements it rendered, as with `within(container)`. + +The request middleware of `src/start.ts` has already run when the callback of `runInRequest` starts, so a mock registered there cannot replace it. A test that needs other behaviour from it registers the mock before `runInRequest`, or passes `globalMiddleware: 'skip'` with the `context` it needs. ## Limits - Vitest is the only supported test runner. +- `runInRequest` sends no HTTP request. A server function call inside it skips the serializer, and a test cannot call a server route through it. +- A test cannot call the handler of a server function without its middleware and its validator. To take a middleware out of the way, replace it with `mockMiddleware`. +- `mockMiddleware` cannot replace a middleware that is created in the same file as a server function that uses it. - The route tree is not regenerated while Vitest watches. diff --git a/e2e/react-start/vitest-app/package.json b/e2e/react-start/vitest-app/package.json index 2b0a83bd35d..5da4ce4ad27 100644 --- a/e2e/react-start/vitest-app/package.json +++ b/e2e/react-start/vitest-app/package.json @@ -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" diff --git a/e2e/react-start/vitest-app/src/components/LikeButton.tsx b/e2e/react-start/vitest-app/src/components/LikeButton.tsx new file mode 100644 index 00000000000..36a3864a1af --- /dev/null +++ b/e2e/react-start/vitest-app/src/components/LikeButton.tsx @@ -0,0 +1,12 @@ +import { useState } from 'react' +import { likePost } from '../posts' + +export function LikeButton({ postId }: { postId: string }) { + const [likes, setLikes] = useState() + + return ( + + ) +} diff --git a/e2e/react-start/vitest-app/src/middleware/auth.ts b/e2e/react-start/vitest-app/src/middleware/auth.ts new file mode 100644 index 00000000000..3adbc956e38 --- /dev/null +++ b/e2e/react-start/vitest-app/src/middleware/auth.ts @@ -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 } }) + }, +) diff --git a/e2e/react-start/vitest-app/src/posts.ts b/e2e/react-start/vitest-app/src/posts.ts index bcefa2c1c98..d8cf71b8eee 100644 --- a/e2e/react-start/vitest-app/src/posts.ts +++ b/e2e/react-start/vitest-app/src/posts.ts @@ -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) + }) diff --git a/e2e/react-start/vitest-app/src/routeTree.gen.ts b/e2e/react-start/vitest-app/src/routeTree.gen.ts index 0168a88c9fc..ae3849a1616 100644 --- a/e2e/react-start/vitest-app/src/routeTree.gen.ts +++ b/e2e/react-start/vitest-app/src/routeTree.gen.ts @@ -95,10 +95,11 @@ export const routeTree = rootRouteImport ._addFileTypes() 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> + config: Awaited> } } diff --git a/e2e/react-start/vitest-app/src/server-only.ts b/e2e/react-start/vitest-app/src/server-only.ts index 446e62b9996..722fcea1fd7 100644 --- a/e2e/react-start/vitest-app/src/server-only.ts +++ b/e2e/react-start/vitest-app/src/server-only.ts @@ -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([ - ['1', { id: '1', title: 'The first post' }], +export interface User { + id: string + name: string +} + +const posts = new Map>([ + ['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() +const users = new Map([['ada', { id: 'u1', name: 'Ada' }]]) +const likes = new Map>() +const calls: Array = [] + +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 { + return calls } diff --git a/e2e/react-start/vitest-app/src/start.ts b/e2e/react-start/vitest-app/src/start.ts new file mode 100644 index 00000000000..7511caa0770 --- /dev/null +++ b/e2e/react-start/vitest-app/src/start.ts @@ -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], +})) diff --git a/e2e/react-start/vitest-app/tests/concurrent-mocks.client.test.tsx b/e2e/react-start/vitest-app/tests/concurrent-mocks.client.test.tsx new file mode 100644 index 00000000000..3fc6b0b976d --- /dev/null +++ b/e2e/react-start/vitest-app/tests/concurrent-mocks.client.test.tsx @@ -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( + + + , + ) +} + +// (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() + }, + ) +} diff --git a/e2e/react-start/vitest-app/tests/like-button.client.test.tsx b/e2e/react-start/vitest-app/tests/like-button.client.test.tsx new file mode 100644 index 00000000000..e36128e8d7a --- /dev/null +++ b/e2e/react-start/vitest-app/tests/like-button.client.test.tsx @@ -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() + + 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' })) +}) diff --git a/e2e/react-start/vitest-app/tests/module-mocks/post-title.test.tsx b/e2e/react-start/vitest-app/tests/module-mocks/post-title.test.tsx index a7a8e2914df..61625654b30 100644 --- a/e2e/react-start/vitest-app/tests/module-mocks/post-title.test.tsx +++ b/e2e/react-start/vitest-app/tests/module-mocks/post-title.test.tsx @@ -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. diff --git a/e2e/react-start/vitest-app/tests/posts.server.test.ts b/e2e/react-start/vitest-app/tests/posts.server.test.ts new file mode 100644 index 00000000000..be065536262 --- /dev/null +++ b/e2e/react-start/vitest-app/tests/posts.server.test.ts @@ -0,0 +1,114 @@ +import { getRouterInstance } from '@tanstack/react-start' +import { getResponseHeader } from '@tanstack/react-start/server' +import { + mockMiddleware, + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' +import { expect, test } from 'vitest' +import { authMiddleware } from '../src/middleware/auth' +import { fetchPost, likePost } from '../src/posts' +import { recordedCalls } from '../src/server-only' + +test('runInRequest resolves to what a server function returns', async () => { + const post = await runInRequest(() => fetchPost({ data: '1' })) + + expect(post.title).toBe('The first post') +}) + +test('a server function runs behind the global middleware of src/start.ts', async () => { + const callsBefore = recordedCalls().length + const post = await runInRequest( + { headers: { 'accept-language': 'de-DE' } }, + () => fetchPost({ data: '1' }), + ) + + expect(post).toEqual({ id: '1', title: 'Der erste Beitrag' }) + // (the global function middleware of the app wrote its audit log) + expect(recordedCalls().slice(callsBefore)).toContain('fetchPost') +}) + +test('a server function fails as in the app', async () => { + await expect( + runInRequest(() => fetchPost({ data: 'unknown' })), + ).rejects.toMatchObject({ isNotFound: true }) +}) + +test('a test checks between two calls and reads what a handler set on the response', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + expect(await likePost({ data: '1' })).toBe(1) + // (a user counts once) + expect(await likePost({ data: '1' })).toBe(1) + + expect(getResponseHeader('cache-control')).toBe('no-store') + }) +}) + +test('the middleware of a server function refuses a request without a session', async () => { + await expect(runInRequest(() => likePost({ data: '1' }))).rejects.toThrow( + 'Not signed in', + ) +}) + +test('mockMiddleware puts a user of the test in place of the session', async () => { + mockMiddleware(authMiddleware, ({ next }) => + next({ context: { user: { id: 'u2', name: 'Grace' } } }), + ) + + await expect(runInRequest(() => likePost({ data: '2' }))).resolves.toBe(1) +}) + +test('runMiddleware calls a middleware on its own', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + const { context } = await runMiddleware(authMiddleware, {}) + + expect(context.user).toEqual({ id: 'u1', name: 'Ada' }) + }) + + await runInRequest(async () => { + await expect(runMiddleware(authMiddleware, {})).rejects.toThrow( + 'Not signed in', + ) + }) +}) + +test('globalMiddleware: skip leaves the middleware of src/start.ts out', async () => { + const callsBefore = recordedCalls().length + + const post = await runInRequest( + { + // (the header would make the request middleware choose German) + headers: { 'accept-language': 'de-DE' }, + globalMiddleware: 'skip', + context: { locale: 'en' }, + }, + () => fetchPost({ data: '3' }), + ) + + expect(post.title).toBe('The third post') + expect(recordedCalls()).toHaveLength(callsBefore) +}) + +test('the context that stands for the global middleware is typed', () => { + // Checked by `tsc` (`test:e2e:types`), never called. + const check = () => [ + // @ts-expect-error the request middleware of src/start.ts passes a locale on + runInRequest({ globalMiddleware: 'skip' }, () => undefined), + runInRequest( + // @ts-expect-error the app has no French + { globalMiddleware: 'skip', context: { locale: 'fr' } }, + () => undefined, + ), + ] + + expect(check).toBeTypeOf('function') +}) + +test('the router of the app is at the URL of the request', async () => { + await runInRequest({ url: '/posts/1?from=test' }, async () => { + const router = await getRouterInstance() + + expect(router.history.location.href).toBe('/posts/1?from=test') + expect(Object.keys(router.routesById)).toContain('/posts/$postId') + }) +}) diff --git a/e2e/react-start/vitest-app/tests/route-tree.client.test.tsx b/e2e/react-start/vitest-app/tests/route-tree.client.test.tsx index 317be71c9f7..f0018c10747 100644 --- a/e2e/react-start/vitest-app/tests/route-tree.client.test.tsx +++ b/e2e/react-start/vitest-app/tests/route-tree.client.test.tsx @@ -4,20 +4,11 @@ import { createMemoryHistory, createRouter, } from '@tanstack/react-router' -import { afterEach, expect, test, vi } from 'vitest' +import { mockServerFn } from '@tanstack/react-start/testing' +import { afterEach, expect, test } from 'vitest' import { fetchPost } from '../src/posts' import { routeTree } from '../src/routeTree.gen' -// A client test has no server: the loader's server function call is answered -// by a module mock. -vi.mock('../src/posts', async (importOriginal) => ({ - ...(await importOriginal()), - fetchPost: vi.fn(async ({ data }: { data: string }) => ({ - id: data, - title: 'Testing with TanStack Start', - })), -})) - afterEach(() => { cleanup() }) @@ -33,6 +24,10 @@ test('the route tree of the client has no server-only route', () => { }) test('a route renders what its loader gets from a server function', async () => { + mockServerFn(fetchPost, ({ data }) => ({ + id: data, + title: 'Testing with TanStack Start', + })) const router = createRouter({ routeTree, history: createMemoryHistory({ initialEntries: ['/posts/42'] }), @@ -43,6 +38,5 @@ test('a route renders what its loader gets from a server function', async () => expect((await screen.findByRole('heading')).textContent).toBe( 'Testing with TanStack Start', ) - expect(fetchPost).toHaveBeenCalledWith({ data: '42' }) expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined() }) diff --git a/e2e/react-start/vitest-app/vite.config.ts b/e2e/react-start/vitest-app/vite.config.ts index d3df28f459c..c3042aa32d9 100644 --- a/e2e/react-start/vitest-app/vite.config.ts +++ b/e2e/react-start/vitest-app/vite.config.ts @@ -5,7 +5,10 @@ import { playwright } from '@vitest/browser-playwright' // A Start app. The same config serves the app and its tests. // -// `test:e2e` type-checks the project and runs these tests three times: +// `test:e2e` type-checks the project in a copy that is installed like a +// user's project (`test:e2e:types`: the workspace installs `vitest` several +// times, once per set of peers, and the types Start adds to Vitest's test +// context reach only one of those copies), then runs these tests three times: // - here, where `@tanstack/*` are links to `packages/*`, with an empty Vitest // cache (`test:e2e:linked`), // - here again, now with the compiled modules of the first run in Vitest's diff --git a/e2e/react-start/vitest-library/package.json b/e2e/react-start/vitest-library/package.json index 6b09b7d62f2..c413c18c962 100644 --- a/e2e/react-start/vitest-library/package.json +++ b/e2e/react-start/vitest-library/package.json @@ -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" diff --git a/e2e/react-start/vitest-library/src/account.ts b/e2e/react-start/vitest-library/src/account.ts new file mode 100644 index 00000000000..a6663262be6 --- /dev/null +++ b/e2e/react-start/vitest-library/src/account.ts @@ -0,0 +1,10 @@ +import { createServerFn } from '@tanstack/react-start' +import { setResponseHeader } from '@tanstack/react-start/server' +import { sessionMiddleware } from './session' + +export const getAccount = createServerFn() + .middleware([sessionMiddleware]) + .handler(({ context }) => { + setResponseHeader('cache-control', 'private') + return { name: context.user } + }) diff --git a/e2e/react-start/vitest-library/src/greeting.ts b/e2e/react-start/vitest-library/src/greeting.ts new file mode 100644 index 00000000000..fb3cf171361 --- /dev/null +++ b/e2e/react-start/vitest-library/src/greeting.ts @@ -0,0 +1,24 @@ +import { createMiddleware, createServerFn } from '@tanstack/react-start' +import { readSecret } from './server-only' + +export const secretMiddleware = createMiddleware({ type: 'function' }) + .client(({ next }) => next({ headers: { 'x-greeting': 'from the client' } })) + .server(({ next }) => next({ context: { secret: readSecret() } })) + +export const greet = createServerFn({ method: 'POST' }) + .middleware([secretMiddleware]) + .validator((name: string) => { + if (!name) { + throw new Error('A name is required') + } + return name + }) + // (typed as a string: a mock returns the type of the handler, and the type + // of this template would be `Hello ${string}, ${string}`) + .handler(({ data, context }): string => `Hello ${data}, ${context.secret}`) + +// Stands for a route loader or a component in the file that defines the +// server function it calls. +export function welcome(name: string) { + return greet({ data: name }) +} diff --git a/e2e/react-start/vitest-library/src/session.ts b/e2e/react-start/vitest-library/src/session.ts new file mode 100644 index 00000000000..24566aa4d53 --- /dev/null +++ b/e2e/react-start/vitest-library/src/session.ts @@ -0,0 +1,23 @@ +import { createMiddleware } from '@tanstack/react-start' +import { getCookie } from '@tanstack/react-start/server' + +// A middleware in a file of its own, so that a test can replace it with +// `mockMiddleware` (see tests/account.server.test.ts). +export const sessionMiddleware = createMiddleware({ type: 'function' }) + .client(({ next }) => { + // Stands for client code that needs a browser. A server test runs the + // client function of a middleware first, as server rendering does. + globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__ = true + return next() + }) + .server(({ next }) => { + const user = getCookie('session') + if (!user) { + throw new Error('Not signed in') + } + return next({ context: { user } }) + }) + +declare global { + var __SESSION_CLIENT_MIDDLEWARE_RAN__: boolean | undefined +} diff --git a/e2e/react-start/vitest-library/src/tenant.ts b/e2e/react-start/vitest-library/src/tenant.ts new file mode 100644 index 00000000000..08f6b9a594d --- /dev/null +++ b/e2e/react-start/vitest-library/src/tenant.ts @@ -0,0 +1,15 @@ +import { createMiddleware } from '@tanstack/react-start' + +// A request middleware: it runs for every request, before any route or +// server function. tests/tenant.server.test.ts runs it on its own. +export const tenantMiddleware = createMiddleware().server( + async ({ next, request }) => { + const tenant = new URL(request.url).hostname.split('.')[0]! + if (tenant === 'www') { + return new Response('No tenant', { status: 404 }) + } + const result = await next({ context: { tenant } }) + result.response.headers.set('x-tenant', tenant) + return result + }, +) diff --git a/e2e/react-start/vitest-library/tests/account.server.test.ts b/e2e/react-start/vitest-library/tests/account.server.test.ts new file mode 100644 index 00000000000..069f83e4df7 --- /dev/null +++ b/e2e/react-start/vitest-library/tests/account.server.test.ts @@ -0,0 +1,97 @@ +import { getRouterInstance } from '@tanstack/react-start' +import { getResponseHeader } from '@tanstack/react-start/server' +import { + mockMiddleware, + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' +import { beforeEach, expect, test } from 'vitest' +import { getAccount } from '../src/account' +import { sessionMiddleware } from '../src/session' + +beforeEach(() => { + globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__ = undefined +}) + +test('a server function cannot be called outside of a request', async () => { + await expect(getAccount()).rejects.toThrow( + /No Start context found.*runInRequest\(\)/, + ) +}) + +test('a server function runs its middleware and its handler for the request of the test', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + await expect(getAccount()).resolves.toEqual({ name: 'ada' }) + + expect(getResponseHeader('cache-control')).toBe('private') + }) + // (as during server rendering, the client function of the middleware ran) + expect(globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__).toBe(true) +}) + +test('runInRequest resolves to what the callback returns', async () => { + const account = await runInRequest( + { headers: { cookie: 'session=ada' } }, + () => getAccount(), + ) + + expect(account).toEqual({ name: 'ada' }) +}) + +test('a server function fails as in the app when its middleware refuses the request', async () => { + await expect(runInRequest(() => getAccount())).rejects.toThrow( + 'Not signed in', + ) +}) + +test('mockMiddleware replaces a middleware, its client function included', async () => { + mockMiddleware(sessionMiddleware, ({ next }) => + next({ context: { user: 'grace' } }), + ) + + await expect(runInRequest(() => getAccount())).resolves.toEqual({ + name: 'grace', + }) + expect(globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__).toBeUndefined() +}) + +test('a mock ends with the test that registered it', async () => { + await expect(runInRequest(() => getAccount())).rejects.toThrow( + 'Not signed in', + ) +}) + +test('a mock registered inside a request ends with that request', async () => { + await runInRequest(async () => { + mockMiddleware(sessionMiddleware, ({ next }) => + next({ context: { user: 'grace' } }), + ) + + await expect(getAccount()).resolves.toEqual({ name: 'grace' }) + }) + + await expect(runInRequest(() => getAccount())).rejects.toThrow( + 'Not signed in', + ) +}) + +test('runMiddleware calls the server function of one middleware', async () => { + await runInRequest({ headers: { cookie: 'session=ada' } }, async () => { + const { context } = await runMiddleware(sessionMiddleware, {}) + + expect(context).toEqual({ user: 'ada' }) + }) + + await runInRequest(async () => { + await expect(runMiddleware(sessionMiddleware, {})).rejects.toThrow( + 'Not signed in', + ) + }) + expect(globalThis.__SESSION_CLIENT_MIDDLEWARE_RAN__).toBeUndefined() +}) + +test('a project without a router entry has no router in a request', async () => { + await expect(runInRequest(() => getRouterInstance())).rejects.toThrow( + 'This project has no router entry', + ) +}) diff --git a/e2e/react-start/vitest-library/tests/greeting.client.test.ts b/e2e/react-start/vitest-library/tests/greeting.client.test.ts new file mode 100644 index 00000000000..9f58c5d6f4c --- /dev/null +++ b/e2e/react-start/vitest-library/tests/greeting.client.test.ts @@ -0,0 +1,39 @@ +import { mockServerFn } from '@tanstack/react-start/testing' +import { expect, test } from 'vitest' +import { greet, welcome } from '../src/greeting' + +test('a mock answers the call with the data of the call', async () => { + mockServerFn(greet, ({ data }) => `Hello ${data}, from the mock`) + + await expect(greet({ data: 'Ada' })).resolves.toBe('Hello Ada, from the mock') +}) + +// The test above registered a mock. Start's setup file ended it with that +// test, so no test of this file removes mocks itself. +test('a server function call without a mock fails with an error that names the function', async () => { + await expect(greet({ data: 'Ada' })).rejects.toThrow( + 'The server function "greet" (/src/greeting.ts) was called in a client test, where no server runs.', + ) +}) + +test('a mock answers a call that is made in the file of the server function', async () => { + mockServerFn(greet, ({ data }) => `Hello ${data}, from the mock`) + + await expect(welcome('Ada')).resolves.toBe('Hello Ada, from the mock') +}) + +test("the function's client middleware runs before the mock", async () => { + let header: string | null = null + mockServerFn(greet, ({ data, headers }) => { + header = headers.get('x-greeting') + return `Hello ${data}, from the mock` + }) + + await greet({ data: 'Ada' }) + + expect(header).toBe('from the client') +}) + +test('the handler, the validator and the server middleware are not in the client code', () => { + expect(globalThis.__SERVER_ONLY_MODULE_LOADED__).toBeUndefined() +}) diff --git a/e2e/react-start/vitest-library/tests/greeting.server.test.ts b/e2e/react-start/vitest-library/tests/greeting.server.test.ts new file mode 100644 index 00000000000..ce80023cdcd --- /dev/null +++ b/e2e/react-start/vitest-library/tests/greeting.server.test.ts @@ -0,0 +1,50 @@ +import { mockServerFn } from '@tanstack/react-start/testing' +import { + mockMiddleware, + runInRequest, +} from '@tanstack/react-start/testing/server' +import { expect, test } from 'vitest' +import { greet, secretMiddleware, welcome } from '../src/greeting' + +test('a server function runs its middleware, its validator and its handler', async () => { + await expect(runInRequest(() => greet({ data: 'Ada' }))).resolves.toBe( + 'Hello Ada, the server secret', + ) +}) + +test('a call that is made in the file of the server function runs it as well', async () => { + await expect(runInRequest(() => welcome('Ada'))).resolves.toBe( + 'Hello Ada, the server secret', + ) +}) + +test('the validator of a server function rejects bad input', async () => { + await expect(runInRequest(() => greet({ data: '' }))).rejects.toThrow( + 'A name is required', + ) +}) + +// On the server a server function runs for real. There is no request that a +// mock could answer. +test('mockServerFn refuses a server function in a server test', () => { + expect(() => + mockServerFn(greet, ({ data }) => `Hello ${data}, from the mock`), + ).toThrow( + 'mockServerFn() needs a server function that the Start compiler compiled for a client test', + ) +}) + +// `secretMiddleware` is created in the file of `greet`. The server loads that +// file a second time for the server side of `greet`, with a middleware object +// of its own, which the mock does not reach. +test('a middleware that is created in the file of its server function cannot be mocked', async () => { + await expect( + runInRequest(async () => { + mockMiddleware(secretMiddleware, ({ next }) => + next({ context: { secret: 'a mocked secret' } }), + ) + + await greet({ data: 'Ada' }) + }), + ).rejects.toThrow('Create the middleware in a file of its own to mock it.') +}) diff --git a/e2e/react-start/vitest-library/tests/tenant.server.test.ts b/e2e/react-start/vitest-library/tests/tenant.server.test.ts new file mode 100644 index 00000000000..3636b8875d9 --- /dev/null +++ b/e2e/react-start/vitest-library/tests/tenant.server.test.ts @@ -0,0 +1,30 @@ +import { + runInRequest, + runMiddleware, +} from '@tanstack/react-start/testing/server' +import { expect, test, vi } from 'vitest' +import { tenantMiddleware } from '../src/tenant' + +test('a request middleware passes context on and can change the response', async () => { + await runInRequest({ url: 'https://acme.example.com/posts' }, async () => { + const { context, response } = await runMiddleware( + tenantMiddleware, + {}, + ({ context }) => new Response(`Posts of ${context.tenant}`), + ) + + expect(context).toEqual({ tenant: 'acme' }) + expect(response.headers.get('x-tenant')).toBe('acme') + await expect(response.text()).resolves.toBe('Posts of acme') + }) +}) + +test('a request middleware can answer the request itself', async () => { + await runInRequest({ url: 'https://www.example.com/posts' }, async () => { + const next = vi.fn() + const { response } = await runMiddleware(tenantMiddleware, {}, next) + + expect(response.status).toBe(404) + expect(next).not.toHaveBeenCalled() + }) +}) diff --git a/e2e/react-start/vitest-library/vitest.config.ts b/e2e/react-start/vitest-library/vitest.config.ts index ac9b6f1b1f0..bbef54b9df9 100644 --- a/e2e/react-start/vitest-library/vitest.config.ts +++ b/e2e/react-start/vitest-library/vitest.config.ts @@ -7,7 +7,10 @@ import { playwright } from '@vitest/browser-playwright' // Start only. It needs the Start compiler, so that each test environment gets // the code a Start app would run there. // -// `test:e2e` type-checks the project and runs these tests three times: +// `test:e2e` type-checks the project in a copy that is installed like a +// user's project (`test:e2e:types`: the workspace installs `vitest` several +// times, once per set of peers, and the types Start adds to Vitest's test +// context reach only one of those copies), then runs these tests three times: // - here, where `@tanstack/*` are links to `packages/*`, with an empty Vitest // cache (`test:e2e:linked`), // - here again, now with the compiled modules of the first run in Vitest's diff --git a/packages/react-start/package.json b/packages/react-start/package.json index 5a0cc7742a3..8c05acdf08a 100644 --- a/packages/react-start/package.json +++ b/packages/react-start/package.json @@ -60,6 +60,24 @@ "default": "./dist/esm/client-rpc.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing.d.ts", + "default": "./dist/esm/testing.js" + } + }, + "./testing/client-rpc": { + "import": { + "types": "./dist/esm/testing/client-rpc.d.ts", + "default": "./dist/esm/testing/client-rpc.js" + } + }, + "./testing/server": { + "import": { + "types": "./dist/esm/testing/server.d.ts", + "default": "./dist/esm/testing/server.js" + } + }, "./server": { "react-server": { "types": "./dist/esm/server.rsc.d.ts", diff --git a/packages/react-start/src/testing.ts b/packages/react-start/src/testing.ts new file mode 100644 index 00000000000..0384b6fb657 --- /dev/null +++ b/packages/react-start/src/testing.ts @@ -0,0 +1,10 @@ +export { + mockServerFn, + resetServerFnMocks, +} from '@tanstack/start-client-core/testing' +export type { + AnyClientServerFn, + ServerFnMock, + ServerFnMockContext, + ServerFnMockData, +} from '@tanstack/start-client-core/testing' diff --git a/packages/react-start/src/testing/client-rpc.ts b/packages/react-start/src/testing/client-rpc.ts new file mode 100644 index 00000000000..80b041a3885 --- /dev/null +++ b/packages/react-start/src/testing/client-rpc.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-client-core/testing/client-rpc' diff --git a/packages/react-start/src/testing/server.ts b/packages/react-start/src/testing/server.ts new file mode 100644 index 00000000000..ec2ad1c8d87 --- /dev/null +++ b/packages/react-start/src/testing/server.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-server-core/testing' diff --git a/packages/react-start/vite.config.ts b/packages/react-start/vite.config.ts index 652e4ef8425..6395099e448 100644 --- a/packages/react-start/vite.config.ts +++ b/packages/react-start/vite.config.ts @@ -29,6 +29,9 @@ export default mergeConfig( './src/client.tsx', './src/hydration.ts', './src/client-rpc.ts', + './src/testing.ts', + './src/testing/client-rpc.ts', + './src/testing/server.ts', './src/server.tsx', './src/server.rsc.ts', './src/server-rpc.ts', diff --git a/packages/solid-start/package.json b/packages/solid-start/package.json index 643b8bc449c..c0d14acb0db 100644 --- a/packages/solid-start/package.json +++ b/packages/solid-start/package.json @@ -57,6 +57,24 @@ "default": "./dist/esm/client-rpc.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing.d.ts", + "default": "./dist/esm/testing.js" + } + }, + "./testing/client-rpc": { + "import": { + "types": "./dist/esm/testing/client-rpc.d.ts", + "default": "./dist/esm/testing/client-rpc.js" + } + }, + "./testing/server": { + "import": { + "types": "./dist/esm/testing/server.d.ts", + "default": "./dist/esm/testing/server.js" + } + }, "./server-rpc": { "import": { "types": "./dist/esm/server-rpc.d.ts", diff --git a/packages/solid-start/src/testing.ts b/packages/solid-start/src/testing.ts new file mode 100644 index 00000000000..0384b6fb657 --- /dev/null +++ b/packages/solid-start/src/testing.ts @@ -0,0 +1,10 @@ +export { + mockServerFn, + resetServerFnMocks, +} from '@tanstack/start-client-core/testing' +export type { + AnyClientServerFn, + ServerFnMock, + ServerFnMockContext, + ServerFnMockData, +} from '@tanstack/start-client-core/testing' diff --git a/packages/solid-start/src/testing/client-rpc.ts b/packages/solid-start/src/testing/client-rpc.ts new file mode 100644 index 00000000000..80b041a3885 --- /dev/null +++ b/packages/solid-start/src/testing/client-rpc.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-client-core/testing/client-rpc' diff --git a/packages/solid-start/src/testing/server.ts b/packages/solid-start/src/testing/server.ts new file mode 100644 index 00000000000..ec2ad1c8d87 --- /dev/null +++ b/packages/solid-start/src/testing/server.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-server-core/testing' diff --git a/packages/solid-start/vite.config.ts b/packages/solid-start/vite.config.ts index 2c1a42d0e49..0e94478654d 100644 --- a/packages/solid-start/vite.config.ts +++ b/packages/solid-start/vite.config.ts @@ -29,6 +29,9 @@ export default mergeConfig( './src/client.tsx', './src/hydration.ts', './src/client-rpc.ts', + './src/testing.ts', + './src/testing/client-rpc.ts', + './src/testing/server.ts', './src/ssr-rpc.ts', './src/server-rpc.ts', './src/server.tsx', diff --git a/packages/start-client-core/package.json b/packages/start-client-core/package.json index c74dce13aa7..9ff363a85da 100644 --- a/packages/start-client-core/package.json +++ b/packages/start-client-core/package.json @@ -60,6 +60,24 @@ "default": "./dist/esm/client-rpc/index.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing/index.d.ts", + "default": "./dist/esm/testing/index.js" + } + }, + "./testing/client-rpc": { + "import": { + "types": "./dist/esm/testing/client-rpc.d.ts", + "default": "./dist/esm/testing/client-rpc.js" + } + }, + "./testing/vitest": { + "import": { + "types": "./dist/esm/testing/vitest.d.ts", + "default": "./dist/esm/testing/vitest.js" + } + }, "./hydration": { "import": { "types": "./dist/esm/hydration.d.ts", @@ -120,5 +138,13 @@ "@arethetypeswrong/cli": "catalog:", "publint": "catalog:", "rimraf": "catalog:" + }, + "peerDependencies": { + "vitest": ">=5.1.1" + }, + "peerDependenciesMeta": { + "vitest": { + "optional": true + } } } diff --git a/packages/start-client-core/src/createMiddleware.ts b/packages/start-client-core/src/createMiddleware.ts index 9b19833d091..2c04474d263 100644 --- a/packages/start-client-core/src/createMiddleware.ts +++ b/packages/start-client-core/src/createMiddleware.ts @@ -511,7 +511,6 @@ export interface FunctionMiddlewareServerFnOptions< > method: Method serverFnMeta: ServerFnMeta - signal: AbortSignal } export type FunctionMiddlewareServerFnResult< diff --git a/packages/start-client-core/src/index.tsx b/packages/start-client-core/src/index.tsx index e9a8b92d854..bda11979a8c 100644 --- a/packages/start-client-core/src/index.tsx +++ b/packages/start-client-core/src/index.tsx @@ -40,6 +40,8 @@ export { type FunctionClientResultWithContext, type AssignAllClientContextBeforeNext, type AssignAllMiddleware, + type AssignAllServerFnContext, + type AssignAllServerRequestContext, type FunctionMiddlewareAfterValidator, type FunctionMiddlewareClientFn, type FunctionMiddlewareServerFnResult, diff --git a/packages/start-client-core/src/testing/client-rpc.ts b/packages/start-client-core/src/testing/client-rpc.ts new file mode 100644 index 00000000000..663386aaec7 --- /dev/null +++ b/packages/start-client-core/src/testing/client-rpc.ts @@ -0,0 +1,2 @@ +// What compiled client code imports in a test run, in place of `../client-rpc`. +export { createClientRpc } from './createClientRpc' diff --git a/packages/start-client-core/src/testing/createClientRpc.ts b/packages/start-client-core/src/testing/createClientRpc.ts new file mode 100644 index 00000000000..6f843973d86 --- /dev/null +++ b/packages/start-client-core/src/testing/createClientRpc.ts @@ -0,0 +1,24 @@ +import { TSS_SERVER_FUNCTION } from '../constants' +import { callServerFnMock, registerClientRpc } from './serverFnMocks' +import type { ClientFnMeta } from '../constants' + +/** + * The `createClientRpc` of a test run. The one of the app sends the call to + * the server (`../client-rpc/createClientRpc`). A client test has no server, + * so this one passes the call to the mock that `mockServerFn` registered. + */ +export function createClientRpc(functionId: string) { + const url = process.env.TSS_SERVER_FN_BASE + functionId + const serverFnMeta: ClientFnMeta = { id: functionId } + registerClientRpc(functionId) + + const clientFn = (...args: Array) => { + return callServerFnMock(functionId, args[0]) + } + + return Object.assign(clientFn, { + url, + serverFnMeta, + [TSS_SERVER_FUNCTION]: true, + }) +} diff --git a/packages/start-client-core/src/testing/index.ts b/packages/start-client-core/src/testing/index.ts new file mode 100644 index 00000000000..3e52d88c245 --- /dev/null +++ b/packages/start-client-core/src/testing/index.ts @@ -0,0 +1,8 @@ +export { mockServerFn, resetServerFnMocks } from './serverFnMocks' +export { MockRegistry } from './mockStores' +export type { + AnyClientServerFn, + ServerFnMock, + ServerFnMockContext, + ServerFnMockData, +} from './serverFnMocks' diff --git a/packages/start-client-core/src/testing/mockStores.ts b/packages/start-client-core/src/testing/mockStores.ts new file mode 100644 index 00000000000..f4a9f65ba49 --- /dev/null +++ b/packages/start-client-core/src/testing/mockStores.ts @@ -0,0 +1,140 @@ +/** + * Where `mockServerFn` and `mockMiddleware` keep their mocks, and how long a + * mock lasts. + * + * A mock belongs to the test that registered it, or to the test file when it + * was registered outside of a test (at the top of the file or in + * `beforeAll`). A test's mocks end with the test. + * + * Which test is running comes from two places: + * + * - The async context of the test, where the test runner provides one (Node, + * and with it jsdom and happy-dom). A call made by code the test started + * then gets that test's mocks, also while other tests run concurrently. + * - Without async context (browser mode), the test that started last. That is + * right for tests that run one after another. Concurrent tests there pass + * their test through the test context (`mockServerFn`, + * `resetServerFnMocks`), and a call gets the mock that was registered last. + * + * A mock registered for a test that has ended, by work the test did not wait + * for, is an error: it would otherwise outlive its test. + */ + +/** A running test, as the test runner identifies it. */ +export type MockOwner = object + +/** Set when the test runner has async context. */ +let getAsyncOwner: (() => MockOwner | undefined) | undefined +/** The tests that have started and not finished, oldest first. */ +const runningOwners = new Set() +const registries = new Set>() + +/** @internal Called by the setup file when the runner has async context. */ +export function setAsyncOwnerSource(source: () => MockOwner | undefined) { + getAsyncOwner = source +} + +/** @internal Called by the setup file before a test runs. */ +export function startTest(owner: MockOwner): void { + runningOwners.add(owner) +} + +/** @internal Called by the setup file after a test and its hooks have run. */ +export function endTest(owner: MockOwner): void { + runningOwners.delete(owner) + for (const registry of registries) { + registry.removeOwner(owner) + } +} + +const ENDED = Symbol('ended test') + +/** + * The test that code runs for: `owner` when one is given, otherwise the test + * of the async context, or without async context the test that started last. + * `undefined` when code runs for no test, `ENDED` when it runs for a test + * that has ended (work the test left running). + */ +function resolveOwner(owner?: MockOwner): MockOwner | undefined | typeof ENDED { + if (!owner && getAsyncOwner) { + owner = getAsyncOwner() + } + if (owner) { + return runningOwners.has(owner) ? owner : ENDED + } + if (getAsyncOwner) { + return undefined + } + let last: MockOwner | undefined + for (const running of runningOwners) { + last = running + } + return last +} + +interface MockEntry { + /** The test the mock belongs to, `undefined` for the file. */ + owner: MockOwner | undefined + value: TValue +} + +/** @internal The mocks of one kind, by what they replace. */ +export class MockRegistry { + /** For each key the mocks of the file and of tests, in registration order. */ + private entries = new Map>>() + + constructor() { + registries.add(this as MockRegistry) + } + + /** Registers for `owner`, or for the test that runs now, or for the file. */ + set(key: TKey, value: TValue, owner?: MockOwner): void { + const resolved = resolveOwner(owner) + if (resolved === ENDED) { + throw new Error( + 'A mock was registered for a test that has already ended. ' + + 'Wait inside the test for the work that registers it.', + ) + } + const entries = (this.entries.get(key) ?? []).filter( + (entry) => entry.owner !== resolved, + ) + entries.push({ owner: resolved, value }) + this.entries.set(key, entries) + } + + get(key: TKey): TValue | undefined { + const asyncOwner = getAsyncOwner?.() + let fileMock: TValue | undefined + let testMock: TValue | undefined + for (const entry of this.entries.get(key) ?? []) { + if (!entry.owner) { + fileMock = entry.value + } else if (!asyncOwner || entry.owner === asyncOwner) { + // (without async context, or from work that lost it, a call cannot + // say which test made it: the mock registered last answers) + testMock = entry.value + } + } + return testMock ?? fileMock + } + + /** Removes the mocks of `owner`, or of the test that runs now, or of the file. */ + clear(owner?: MockOwner): void { + const resolved = resolveOwner(owner) + if (resolved !== ENDED) { + this.removeOwner(resolved) + } + } + + removeOwner(owner: MockOwner | undefined): void { + for (const [key, entries] of this.entries) { + const kept = entries.filter((entry) => entry.owner !== owner) + if (kept.length) { + this.entries.set(key, kept) + } else { + this.entries.delete(key) + } + } + } +} diff --git a/packages/start-client-core/src/testing/serverFnMocks.ts b/packages/start-client-core/src/testing/serverFnMocks.ts new file mode 100644 index 00000000000..b7ddfde21dd --- /dev/null +++ b/packages/start-client-core/src/testing/serverFnMocks.ts @@ -0,0 +1,176 @@ +import { MockRegistry } from './mockStores' +import type { MockOwner } from './mockStores' +import type { FetcherBase, Method } from '../createServerFn' + +/** + * Answers for the server function calls of client tests. + * + * A client test has no server. So when a test runner compiles a project, the + * client code of a server function gets the `createClientRpc` of + * `./createClientRpc` instead of the one that sends a request. That one asks + * this module for the answer a test registered with `mockServerFn`, and fails + * when there is none. + */ + +/** What a mock gets of a server function call. */ +export interface ServerFnMockContext { + /** + * The `data` of the call, as the caller passed it. The function's validator + * has not run: it runs on the server, which the mock stands for. + */ + data: TData + method: Method + /** The headers of the call, with what the function's client middleware added. */ + headers: Headers + signal: AbortSignal | undefined +} + +/** A server function as client code has it. */ +export type AnyClientServerFn = FetcherBase & + ((...args: Array) => Promise) + +/** The `data` a server function is called with. */ +export type ServerFnMockData = TServerFn extends ( + options: infer TOptions, + ...args: Array +) => unknown + ? 'data' extends keyof NonNullable + ? NonNullable['data'] + : undefined + : never + +/** + * Stands for everything of a server function that runs on the server: its + * server middleware, its validator and its handler. It returns what the call + * resolves to, or throws what the call rejects with. + */ +export type ServerFnMock = ( + ctx: ServerFnMockContext>, +) => Awaited> | Promise>> + +type AnyServerFnMock = (ctx: ServerFnMockContext) => unknown + +declare module 'vitest' { + interface TestContext { + /** + * `mockServerFn` for this test. The mock ends with this test also when + * other tests run concurrently, in every test environment. + */ + mockServerFn: ( + serverFn: TServerFn, + mock: ServerFnMock, + ) => void + /** `resetServerFnMocks` for this test: removes the mocks of this test. */ + resetServerFnMocks: () => void + } +} + +/** The ids of the server functions that were compiled for this client test. */ +const clientRpcIds = new Set() +const mocks = new MockRegistry() + +/** + * Answers the calls of a server function in a client test. A mock that a test + * or a `beforeEach` hook registers ends with that test; one from the top of + * the file or from `beforeAll` stays for the file. The mock is typed from the + * server function: it gets the `data` the function is called with, and + * returns what the function's handler returns. + * + * The function's client middleware runs as in the app. The mock is called + * where the app would send the request. + * + * Tests that run concurrently in browser mode use the `mockServerFn` of their + * test context instead, so that each mock ends with its own test. + */ +export function mockServerFn( + serverFn: TServerFn, + mock: ServerFnMock, +): void { + registerServerFnMock(serverFn, mock, undefined) +} + +/** @internal `mockServerFn` for a given test: the one of the test context. */ +export function registerServerFnMock( + serverFn: TServerFn, + mock: ServerFnMock, + owner: MockOwner | undefined, +): void { + const id = (serverFn as { serverFnMeta?: { id?: string } }).serverFnMeta?.id + if (id === undefined || !clientRpcIds.has(id)) { + throw new Error( + 'mockServerFn() needs a server function that the Start compiler compiled for a client test: ' + + 'one created with createServerFn().handler(), imported in a test that runs in a browser, in jsdom or in happy-dom, ' + + "with Start's plugin in the test runner's config. " + + 'In a server test a server function runs for real and has no request to answer.', + ) + } + mocks.set(id, mock as AnyServerFnMock, owner) +} + +/** + * Removes the mocks of `mockServerFn` now: the ones of the running test when + * it is called in a test, the ones of the file otherwise. Mocks end with + * their test anyway, so this is only for removing them earlier. + */ +export function resetServerFnMocks(): void { + mocks.clear() +} + +/** @internal `resetServerFnMocks` for a given test: the one of the test context. */ +export function resetServerFnMocksOf(owner: MockOwner): void { + mocks.clear(owner) +} + +/** Called by the `createClientRpc` of a test run for each function it creates. */ +export function registerClientRpc(id: string): void { + clientRpcIds.add(id) +} + +/** + * Called by the `createClientRpc` of a test run in place of the request. + * Resolves to what the response of the server would be read as. + */ +export async function callServerFnMock( + id: string, + call: { + data?: unknown + method: Method + headers?: HeadersInit + signal?: AbortSignal + }, +): Promise<{ result: unknown }> { + const mock = mocks.get(id) + if (!mock) { + throw new Error( + `The server function ${describeServerFn(id)} was called in a client test, where no server runs. ` + + 'Answer the call with mockServerFn() before it is made.', + ) + } + return { + result: await mock({ + data: call.data, + method: call.method, + headers: new Headers(call.headers), + signal: call.signal, + }), + } +} + +/** + * The name and the file of a server function, read from its id. The compiler + * of a dev server or a test run encodes both in the id. + */ +function describeServerFn(id: string): string { + try { + const bytes = Uint8Array.from( + atob(id.replace(/-/g, '+').replace(/_/g, '/')), + (char) => char.charCodeAt(0), + ) + const { file, export: exportName } = JSON.parse( + new TextDecoder().decode(bytes), + ) as { file: string; export: string } + return `"${exportName.replace(/_createServerFn_handler$/, '')}" (${file.replace(/\?.*$/, '')})` + } catch { + return `with the id "${id}"` + } +} diff --git a/packages/start-client-core/src/testing/vitest.ts b/packages/start-client-core/src/testing/vitest.ts new file mode 100644 index 00000000000..62e4cc85ab2 --- /dev/null +++ b/packages/start-client-core/src/testing/vitest.ts @@ -0,0 +1,35 @@ +// The setup file Start's plugin adds to a Vitest run. It tells the mocks of +// `mockServerFn` and `mockMiddleware` which test runs, so that each mock ends +// with the test that registered it (./mockStores.ts). +import { aroundEach, beforeEach } from 'vitest' +import { endTest, setAsyncOwnerSource, startTest } from './mockStores' +import { registerServerFnMock, resetServerFnMocksOf } from './serverFnMocks' + +/** `AsyncLocalStorage`, where the test runs in Node (also jsdom, happy-dom). */ +async function loadAsyncLocalStorage() { + try { + const { AsyncLocalStorage } = await import('node:async_hooks') + return AsyncLocalStorage + } catch { + // (browser mode: the module is a stub that throws when it is read) + return undefined + } +} + +const AsyncLocalStorage = await loadAsyncLocalStorage() +if (AsyncLocalStorage) { + const tests = new AsyncLocalStorage() + setAsyncOwnerSource(() => tests.getStore()) + aroundEach((runTest, context) => tests.run(context.task, runTest)) +} + +beforeEach((context) => { + const owner = context.task + startTest(owner) + // (the hook of the test context: Vitest's global hooks do not know which of + // several concurrent tests finished) + context.onTestFinished(() => endTest(owner)) + context.mockServerFn = (serverFn, mock) => + registerServerFnMock(serverFn, mock, owner) + context.resetServerFnMocks = () => resetServerFnMocksOf(owner) +}) diff --git a/packages/start-client-core/src/tests/serverFnMocks.test-d.ts b/packages/start-client-core/src/tests/serverFnMocks.test-d.ts new file mode 100644 index 00000000000..f8354fc2fb8 --- /dev/null +++ b/packages/start-client-core/src/tests/serverFnMocks.test-d.ts @@ -0,0 +1,58 @@ +import { expectTypeOf, test } from 'vitest' +import { createServerFn } from '../createServerFn' +import { mockServerFn } from '../testing/index' +import type { ServerFnMockContext } from '../testing/index' + +const getUser = createServerFn({ method: 'POST' }) + .validator((input: { id: string }) => input) + .handler(({ data }) => ({ id: data.id, age: data.id.length })) + +const getTime = createServerFn().handler(() => Date.now()) + +const search = createServerFn() + .validator((input?: { query: string }) => input) + .handler(({ data }) => data?.query.split(' ') ?? []) + +test('a mock gets the data the server function is called with', () => { + mockServerFn(getUser, (ctx) => { + expectTypeOf(ctx).toEqualTypeOf>() + expectTypeOf(ctx.data).toEqualTypeOf<{ id: string }>() + expectTypeOf(ctx.method).toEqualTypeOf<'GET' | 'POST'>() + expectTypeOf(ctx.headers).toEqualTypeOf() + expectTypeOf(ctx.signal).toEqualTypeOf() + return { id: ctx.data.id, age: 1 } + }) +}) + +test('a mock of a server function without input gets no data', () => { + mockServerFn(getTime, ({ data }) => { + expectTypeOf(data).toEqualTypeOf() + return 0 + }) +}) + +test('a mock of a server function with optional input may get no data', () => { + mockServerFn(search, ({ data }) => { + expectTypeOf(data).toEqualTypeOf<{ query: string } | undefined>() + return [] + }) +}) + +test('a mock returns what the handler returns, now or later', () => { + mockServerFn(getUser, () => ({ id: 'a', age: 1 })) + mockServerFn(getUser, async () => ({ id: 'a', age: 1 })) + + // @ts-expect-error the handler returns an object + mockServerFn(getUser, () => 'a') + // @ts-expect-error the age of the handler's object is a number + mockServerFn(getUser, async () => ({ id: 'a', age: 'old' })) + // @ts-expect-error the handler returns a number + mockServerFn(getTime, () => 'now') +}) + +test('only a server function can be mocked', () => { + const plain = async (options: { data: string }) => options.data + + // @ts-expect-error a plain function is no server function + mockServerFn(plain, () => '') +}) diff --git a/packages/start-client-core/tests/mockStores.async-context.test.ts b/packages/start-client-core/tests/mockStores.async-context.test.ts new file mode 100644 index 00000000000..ed4782e4f60 --- /dev/null +++ b/packages/start-client-core/tests/mockStores.async-context.test.ts @@ -0,0 +1,87 @@ +// The mock registry with async context, as in Node, jsdom and happy-dom. +import { AsyncLocalStorage } from 'node:async_hooks' +import { expect, test } from 'vitest' +import { + MockRegistry, + endTest, + setAsyncOwnerSource, + startTest, +} from '../src/testing/mockStores' + +const tests = new AsyncLocalStorage() +setAsyncOwnerSource(() => tests.getStore()) + +function runTest(body: () => Promise) { + const owner = {} + startTest(owner) + return tests.run(owner, body).finally(() => endTest(owner)) +} + +test('concurrent tests that mock the same key each get their own mock', async () => { + const registry = new MockRegistry() + const seen: Array = [] + const later = () => new Promise((resolve) => setTimeout(resolve, 5)) + + await Promise.all([ + runTest(async () => { + registry.set('fn', 'mock of A') + await later() + seen.push(registry.get('fn')) + }), + runTest(async () => { + registry.set('fn', 'mock of B') + await later() + seen.push(registry.get('fn')) + }), + ]) + + expect(seen.sort()).toEqual(['mock of A', 'mock of B']) + expect(registry.get('fn')).toBeUndefined() +}) + +test('a mock registered outside of a test belongs to the file, also while a test runs', async () => { + const registry = new MockRegistry() + + await runTest(async () => { + // (as in a beforeAll hook, which runs outside of any test's context) + tests.exit(() => registry.set('fn', 'file mock')) + expect(registry.get('fn')).toBe('file mock') + }) + + expect(registry.get('fn')).toBe('file mock') +}) + +// Work a test leaves running keeps the test's async context after the test +// has ended. A mock it registered became a mock of the file. +test('a mock registered for a test that has ended is an error', async () => { + const registry = new MockRegistry() + let resume!: () => void + const resumed = new Promise((resolve) => (resume = resolve)) + let late: Promise | undefined + + await runTest(async () => { + late = resumed.then(() => registry.set('fn', 'late mock')) + }) + resume() + + await expect(late).rejects.toThrow( + 'A mock was registered for a test that has already ended.', + ) + expect(registry.get('fn')).toBeUndefined() +}) + +test('a reset for a test that has ended leaves the mocks of the file', async () => { + const registry = new MockRegistry() + registry.set('fn', 'file mock') + let resume!: () => void + const resumed = new Promise((resolve) => (resume = resolve)) + let late: Promise | undefined + + await runTest(async () => { + late = resumed.then(() => registry.clear()) + }) + resume() + await late + + expect(registry.get('fn')).toBe('file mock') +}) diff --git a/packages/start-client-core/tests/mockStores.test.ts b/packages/start-client-core/tests/mockStores.test.ts new file mode 100644 index 00000000000..c324f632c8d --- /dev/null +++ b/packages/start-client-core/tests/mockStores.test.ts @@ -0,0 +1,112 @@ +// The mock registry without async context, as in Vitest's browser mode. +import { expect, test } from 'vitest' +import { MockRegistry, endTest, startTest } from '../src/testing/mockStores' + +test('a mock of a test ends with the test, and the mocks of the file stay', () => { + const registry = new MockRegistry() + registry.set('fn', 'file mock') + const testA = {} + + startTest(testA) + registry.set('fn', 'mock of A') + expect(registry.get('fn')).toBe('mock of A') + endTest(testA) + + expect(registry.get('fn')).toBe('file mock') +}) + +test('a mock passed for a test ends with that test, while another test runs too', () => { + const registry = new MockRegistry() + const testA = {} + const testB = {} + startTest(testA) + startTest(testB) + + registry.set('first', 'mock of A', testA) + registry.set('second', 'mock of B', testB) + endTest(testA) + + expect(registry.get('first')).toBeUndefined() + expect(registry.get('second')).toBe('mock of B') + endTest(testB) +}) + +// Without async context a call cannot say which test made it. +test('the mock registered last answers a call when two tests mock the same key', () => { + const registry = new MockRegistry() + const testA = {} + const testB = {} + startTest(testA) + startTest(testB) + + registry.set('fn', 'mock of A', testA) + registry.set('fn', 'mock of B', testB) + expect(registry.get('fn')).toBe('mock of B') + + endTest(testB) + expect(registry.get('fn')).toBe('mock of A') + endTest(testA) +}) + +// The order is per key: a later registration of A for another key does not +// make A's older mock of `fn` the latest one. +test('the latest registration for a key answers, whatever else was registered since', () => { + const registry = new MockRegistry() + const testA = {} + const testB = {} + startTest(testA) + startTest(testB) + + registry.set('fn', 'mock of A', testA) + registry.set('fn', 'mock of B', testB) + registry.set('other', 'other mock of A', testA) + expect(registry.get('fn')).toBe('mock of B') + + endTest(testB) + expect(registry.get('fn')).toBe('mock of A') + endTest(testA) +}) + +test('clear() for a given test removes the mocks of that test, while another test runs too', () => { + const registry = new MockRegistry() + const testA = {} + const testB = {} + startTest(testA) + startTest(testB) + registry.set('first', 'mock of A', testA) + registry.set('second', 'mock of B', testB) + + // (without async context the test that started last is B) + registry.clear(testA) + + expect(registry.get('first')).toBeUndefined() + expect(registry.get('second')).toBe('mock of B') + endTest(testA) + endTest(testB) +}) + +test('clear() in a test removes only the mocks of that test', () => { + const registry = new MockRegistry() + registry.set('fn', 'file mock') + const testA = {} + startTest(testA) + registry.set('fn', 'mock of A') + + registry.clear() + + expect(registry.get('fn')).toBe('file mock') + endTest(testA) +}) + +// A registry is created when its module loads. When a test loads it with a +// dynamic import(), the mocks it then registered stayed for the next test. +test('a registry created during a test ends the mocks of that test too', () => { + const testA = {} + startTest(testA) + const lateRegistry = new MockRegistry() + lateRegistry.set('fn', 'mock of A') + + endTest(testA) + + expect(lateRegistry.get('fn')).toBeUndefined() +}) diff --git a/packages/start-client-core/tests/serverFnMocks.test.ts b/packages/start-client-core/tests/serverFnMocks.test.ts new file mode 100644 index 00000000000..4c1a3dd81e1 --- /dev/null +++ b/packages/start-client-core/tests/serverFnMocks.test.ts @@ -0,0 +1,192 @@ +import { afterEach, describe, expect, test } from 'vitest' +import { runWithStartContext } from '@tanstack/start-storage-context' +import { redirect } from '@tanstack/router-core' +import { createMiddleware } from '../src/createMiddleware' +import { createServerFn } from '../src/createServerFn' +import { resetServerFnMocks, mockServerFn } from '../src/testing' +import { createClientRpc } from '../src/testing/client-rpc' +import type { AnyClientServerFn } from '../src/testing' + +/** The id the compiler of a dev server or a test run gives a server function. */ +function devId(name: string, file = '/src/greeting.ts') { + return Buffer.from( + JSON.stringify({ + file: `${file}?tss-serverfn-split`, + export: `${name}_createServerFn_handler`, + }), + ).toString('base64url') +} + +type Greet = AnyClientServerFn & + ((options: { data: string }) => Promise) + +/** + * A server function as the compiler leaves it in the client code of a test + * run: `.handler()` gets `createClientRpc(id)` in place of the handler. + */ +function clientServerFn( + id: string, + builder: { handler: unknown } = createServerFn({ method: 'POST' }), +) { + return (builder.handler as (extractedFn: unknown) => Greet)( + createClientRpc(id), + ) +} + +/** + * This package's own code is not compiled, so Start's isomorphic functions + * run their server implementation here and need a request context. + */ +function call(fn: () => Promise) { + return runWithStartContext( + { + getRouter() { + throw new Error('A server function call does not need a router') + }, + request: new Request('http://localhost/'), + startOptions: {}, + contextAfterGlobalMiddlewares: {}, + executedRequestMiddlewares: new Set(), + handlerType: 'serverFn', + }, + fn, + ) +} + +afterEach(() => { + resetServerFnMocks() +}) + +describe('a server function call in a client test', () => { + test('resolves to what its mock returns for the data of the call', async () => { + const greet = clientServerFn(devId('greet')) + mockServerFn(greet, ({ data, method }) => `Hello ${data} by ${method}`) + + await expect(call(() => greet({ data: 'Ada' }))).resolves.toBe( + 'Hello Ada by POST', + ) + }) + + test('resolves to what an async mock resolves to', async () => { + const greet = clientServerFn(devId('greet')) + mockServerFn(greet, async ({ data }) => `Hello ${data}`) + + await expect(call(() => greet({ data: 'Ada' }))).resolves.toBe('Hello Ada') + }) + + test("runs the function's client middleware, and the mock gets the headers it adds", async () => { + const order: Array = [] + const greet = clientServerFn( + devId('greet'), + createServerFn({ method: 'POST' }).middleware([ + createMiddleware({ type: 'function' }).client(async ({ next }) => { + order.push('client middleware before') + const result = await next({ headers: { 'x-from-client': 'yes' } }) + order.push('client middleware after') + return result + }), + ]), + ) + mockServerFn(greet, ({ headers }) => { + order.push('mock') + return `x-from-client: ${headers.get('x-from-client')}` + }) + + await expect(call(() => greet({ data: 'Ada' }))).resolves.toBe( + 'x-from-client: yes', + ) + expect(order).toEqual([ + 'client middleware before', + 'mock', + 'client middleware after', + ]) + }) + + test('rejects with what its mock throws', async () => { + const greet = clientServerFn(devId('greet')) + const failure = new Error('No such user') + mockServerFn(greet, () => { + throw failure + }) + + await expect(call(() => greet({ data: 'Ada' }))).rejects.toBe(failure) + }) + + test('rejects with the redirect its mock throws', async () => { + const greet = clientServerFn(devId('greet')) + const toLogin = redirect({ to: '/login' }) + mockServerFn(greet, () => { + throw toLogin + }) + + await expect(call(() => greet({ data: 'Ada' }))).rejects.toBe(toLogin) + }) + + test('is answered by the last mock of the function', async () => { + const greet = clientServerFn(devId('greet')) + mockServerFn(greet, () => 'first') + mockServerFn(greet, () => 'second') + + await expect(call(() => greet({ data: 'Ada' }))).resolves.toBe('second') + }) + + test('without a mock rejects with an error that names the function and its file', async () => { + const greet = clientServerFn(devId('greet', '/src/features/greeting.ts')) + + await expect(call(() => greet({ data: 'Ada' }))).rejects.toThrow( + 'The server function "greet" (/src/features/greeting.ts) was called in a client test, where no server runs. Answer the call with mockServerFn() before it is made.', + ) + }) + + test('without a mock rejects with an error that has the id, when the id names no function', async () => { + const greet = clientServerFn('3f9a1c') + + await expect(call(() => greet({ data: 'Ada' }))).rejects.toThrow( + 'The server function with the id "3f9a1c" was called in a client test', + ) + }) + + test('has no mock after resetServerFnMocks', async () => { + const greet = clientServerFn(devId('greet')) + mockServerFn(greet, () => 'mocked') + + resetServerFnMocks() + + await expect(call(() => greet({ data: 'Ada' }))).rejects.toThrow( + 'was called in a client test', + ) + }) + + test('of one function is not answered by the mock of another', async () => { + const greet = clientServerFn(devId('greet')) + const farewell = clientServerFn(devId('farewell')) + mockServerFn(greet, () => 'Hello') + + await expect(call(() => farewell({ data: 'Ada' }))).rejects.toThrow( + 'The server function "farewell"', + ) + }) +}) + +describe('mockServerFn', () => { + // The server's and the app's own versions of a server function have an id + // too, but no test answers their calls. + test('refuses a server function that was not compiled for a client test', () => { + const notForATest = Object.assign(async () => 'sent', { + url: '/_serverFn/abc', + serverFnMeta: { id: 'abc' }, + }) as unknown as Greet + + expect(() => mockServerFn(notForATest, () => 'mocked')).toThrow( + 'mockServerFn() needs a server function that the Start compiler compiled for a client test', + ) + }) + + test('refuses a function that is no server function', () => { + const plain = (async () => 'plain') as unknown as Greet + + expect(() => mockServerFn(plain, () => 'mocked')).toThrow( + 'mockServerFn() needs a server function', + ) + }) +}) diff --git a/packages/start-client-core/vite.config.ts b/packages/start-client-core/vite.config.ts index 71e163a1ed9..597d0376ba9 100644 --- a/packages/start-client-core/vite.config.ts +++ b/packages/start-client-core/vite.config.ts @@ -25,6 +25,9 @@ export default defineConfig(({ command }) => './src/index.tsx', './src/client/index.ts', './src/client-rpc/index.ts', + './src/testing/index.ts', + './src/testing/client-rpc.ts', + './src/testing/vitest.ts', './src/hydration/constants.ts', './src/hydration.ts', './src/hydration/runtime.ts', diff --git a/packages/start-plugin-core/AGENTS.md b/packages/start-plugin-core/AGENTS.md index bd0fe0f2bd9..f6d68df75eb 100644 --- a/packages/start-plugin-core/AGENTS.md +++ b/packages/start-plugin-core/AGENTS.md @@ -6,3 +6,4 @@ - Use a built Start e2e app to validate generated imports and runtime behavior together; compiler snapshots alone do not exercise that integration. - The shared compiler serves both Vite and Rsbuild. For shared compiler changes, check the relevant adapter suites in `tests/vite/` and `tests/rsbuild/`, plus affected Start e2e modes for build, server-function, or HMR behavior. - A test run (`isVitestRun`) gets its own config plan. A run inside this repository cannot show a mistake in what it tells Vite or Vitest about packages (`resolve.noExternal`, `optimizeDeps`); check changes with the `test:e2e:installed` script of `e2e/react-start/vitest-*` ([why](../../scripts/e2e/run-as-installed.md)). +- Vitest keeps compiled modules on disk across runs, so in a test run the compiler may never see a file. Nothing a test run needs may depend on what the compiler recorded in the process (the server function resolver of a test run skips the id check for that reason). `test:e2e:cached` of `e2e/react-start/vitest-*` runs the tests from that cache. diff --git a/packages/start-plugin-core/package.json b/packages/start-plugin-core/package.json index 11b100715d2..e279897a09c 100644 --- a/packages/start-plugin-core/package.json +++ b/packages/start-plugin-core/package.json @@ -116,6 +116,7 @@ "@tanstack/router-generator": "workspace:*", "@tanstack/router-plugin": "workspace:*", "@tanstack/router-utils": "workspace:*", + "@tanstack/start-client-core": "workspace:*", "@tanstack/start-server-core": "workspace:*", "exsolve": "^1.1.3", "lightningcss": "^1.33.0", diff --git a/packages/start-plugin-core/src/vite/planning.ts b/packages/start-plugin-core/src/vite/planning.ts index f98d8ad8c7b..6964e426520 100644 --- a/packages/start-plugin-core/src/vite/planning.ts +++ b/packages/start-plugin-core/src/vite/planning.ts @@ -147,6 +147,11 @@ export function createViteTestConfigPlan(opts: { if (opts.entryPaths.router) { alias[ENTRY_POINTS.router] = normalizePath(opts.entryPaths.router) } + // Compiled client code imports `createClientRpc` from this module. No + // server takes the request of a client test, so the call goes to the mock + // that `mockServerFn` registered instead. + alias[`@tanstack/${opts.framework}-start/client-rpc`] = + `@tanstack/${opts.framework}-start/testing/client-rpc` return { environments: { diff --git a/packages/start-plugin-core/src/vite/plugin.ts b/packages/start-plugin-core/src/vite/plugin.ts index c2ce6b898ee..c712db37f2d 100644 --- a/packages/start-plugin-core/src/vite/plugin.ts +++ b/packages/start-plugin-core/src/vite/plugin.ts @@ -39,7 +39,11 @@ import { } from './output-directory' import { postServerBuild } from './post-server-build' import { serializationAdaptersPlugin } from './serialization-adapters-plugin' -import { excludeFromTestRuns, testRunRouterEntryPlugin } from './test-run' +import { + excludeFromTestRuns, + testRunRouterEntryPlugin, + vitestSetupFilePlugin, +} from './test-run' import type { TanStackStartVitePluginCoreOptions, ViteRscForwardSsrResolverStrategy, @@ -262,6 +266,7 @@ export function tanStackStartVite( serverFnProviderModuleDirectives: corePluginOpts.serverFnProviderModuleDirectives, providerEnvName: serverFnProviderEnv, + isTestRun, }), importProtectionPlugin({ getConfig, @@ -276,6 +281,7 @@ export function tanStackStartVite( isTestRun, ), loadEnvPlugin(), + vitestSetupFilePlugin(isTestRun), testRunRouterEntryPlugin(), excludeFromTestRuns( createDevClientEntryPlugin({ diff --git a/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts b/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts index 3a93e286d11..de224bc8f39 100644 --- a/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts +++ b/packages/start-plugin-core/src/vite/start-compiler-plugin/plugin.ts @@ -200,11 +200,24 @@ function invalidateModuleNodes( } } -function getDevServerFnValidatorModule(): string { - return ` -export async function getServerFnById(id, _access) { +/** + * The resolver of a dev server. A function id names the file and the export + * of the function. `validateId` first asks the compiler whether it compiled + * a server function with that id, because a dev server takes ids from HTTP + * requests. + * + * A test run passes `validateId: false`. No request reaches it from outside, + * and a test runner can serve a compiled file from its cache, so that the + * compiler never sees the file and has no record of its functions. + */ +function getDevServerFnResolverModule(opts: { validateId: boolean }): string { + const validateId = opts.validateId + ? ` const validateIdImport = ${JSON.stringify(validateServerFnIdVirtualModule)} + '?id=' + id - await import(/* @vite-ignore */ '/@id/__x00__' + validateIdImport) + await import(/* @vite-ignore */ '/@id/__x00__' + validateIdImport)` + : '' + return ` +export async function getServerFnById(id, _access) {${validateId} const decoded = Buffer.from(id, 'base64url').toString('utf8') const devServerFn = JSON.parse(decoded) const mod = await import(/* @vite-ignore */ devServerFn.file) @@ -243,6 +256,11 @@ export interface StartCompilerPluginOptions { * The Vite environment name for the server function provider. */ providerEnvName: string + /** + * Whether the bundler runs for a test runner. The resolver of a test run + * finds a server function without the compiler's record of it. + */ + isTestRun?: () => boolean } export function startCompilerPlugin( @@ -670,7 +688,9 @@ export function startCompilerPlugin( } if (this.environment.mode !== 'build') { - return getDevServerFnValidatorModule() + return getDevServerFnResolverModule({ + validateId: !opts.isTestRun?.(), + }) } // When SSR is the provider, server-only-referenced functions aren't in the manifest, diff --git a/packages/start-plugin-core/src/vite/test-run.ts b/packages/start-plugin-core/src/vite/test-run.ts index d020134e1f3..3d0abf5b87d 100644 --- a/packages/start-plugin-core/src/vite/test-run.ts +++ b/packages/start-plugin-core/src/vite/test-run.ts @@ -1,3 +1,5 @@ +import { fileURLToPath } from 'node:url' +import { normalizePath } from 'vite' import { ENTRY_POINTS } from '../constants' import { isVitestRun } from '../test-mode' import { createVirtualModule } from './createVirtualModule' @@ -34,6 +36,44 @@ export function excludeFromTestRuns(option: PluginOption): PluginOption { } } +/** The part of a Vitest project that a plugin may change. */ +interface VitestProject { + config: { setupFiles: Array } +} + +/** Vitest calls this hook of a Vite plugin for each of its projects. */ +interface VitestPluginHooks { + configureVitest?: (context: { project: VitestProject }) => void +} + +/** + * Adds Start's setup file to every Vitest project of a test run. The file + * ends the mocks of `mockServerFn` and `mockMiddleware` with the test that + * registered them. + * + * The file goes in through `configureVitest`, because `test.setupFiles` + * returned from the `config` hook only reaches a browser project. + */ +export function vitestSetupFilePlugin(isTestRun: () => boolean): Plugin { + const plugin: Plugin & VitestPluginHooks = { + name: 'tanstack-start-core:vitest-setup-file', + configureVitest({ project }) { + if (!isTestRun()) { + return + } + const setupFile = normalizePath( + fileURLToPath( + import.meta.resolve('@tanstack/start-client-core/testing/vitest'), + ), + ) + if (!project.config.setupFiles.includes(setupFile)) { + project.config.setupFiles.push(setupFile) + } + }, + } + return plugin +} + /** * Answers the import of the router entry in a test run of a project that has * none, such as a package that only uses Start's compile-time APIs. Start's diff --git a/packages/start-plugin-core/tests/integration/start-test-run.test.ts b/packages/start-plugin-core/tests/integration/start-test-run.test.ts index ded8bca7905..a38b2b90f87 100644 --- a/packages/start-plugin-core/tests/integration/start-test-run.test.ts +++ b/packages/start-plugin-core/tests/integration/start-test-run.test.ts @@ -83,8 +83,11 @@ export const where = createIsomorphicFn() timeout, ) + // A client test has no server to send a server function call to. The + // client code gets the `createClientRpc` that asks `mockServerFn`'s mocks, + // in place of the one that sends the request. test( - 'the client code of a server function has no handler', + "the client code of a server function calls the test's mocks, not a server", async () => { const app = await createStartApp( { @@ -99,6 +102,42 @@ export const greet = createServerFn({ method: 'POST' }).handler(() => 'MARK_HAND const client = await compiled(server, 'client', 'src/greeting.ts') expect(client).not.toContain('MARK_HANDLER') + expect(client).toMatch(/react-start\/dist\/esm\/testing\/client-rpc\.js/) + }, + timeout, + ) + + // A test runner can keep compiled modules across runs (Vitest does, on + // disk). The call site of a server function then comes from that cache, the + // compiler of the new process never sees it and has no record of the + // function. The resolver asked the compiler for that record and failed + // with "Invalid server function ID". + test( + 'the server finds a server function whose call site this process did not compile', + async () => { + const app = await createStartApp( + { + 'src/greeting.ts': `import { createServerFn } from '@tanstack/react-start' +export const greet = createServerFn({ method: 'POST' }).handler(() => 'MARK_HANDLER') +`, + }, + 'start-library-', + ) + const earlier = await startViteTestServer(app) + const callSite = await compiled(earlier.server, 'ssr', 'src/greeting.ts') + const id = /createSsrRpc\)?\(\s*["']([^"']+)["']/.exec(callSite)?.[1] + expect(id).toBeTypeOf('string') + await earlier.server.close() + + const { server } = await startViteTestServer(app) + const resolver = await importOnServer( + server, + '#tanstack-start-server-fn-resolver', + ) + + const serverFn = await resolver.getServerFnById(id, { origin: 'server' }) + expect(serverFn).toBeTypeOf('function') + expect(serverFn.serverFnMeta).toMatchObject({ name: 'greet' }) }, timeout, ) diff --git a/packages/start-plugin-core/tests/vite/test-config-plan.test.ts b/packages/start-plugin-core/tests/vite/test-config-plan.test.ts index 64a022b8b35..6cd790c1a76 100644 --- a/packages/start-plugin-core/tests/vite/test-config-plan.test.ts +++ b/packages/start-plugin-core/tests/vite/test-config-plan.test.ts @@ -42,6 +42,24 @@ describe('createViteTestConfigPlan', () => { expect(ENTRY_POINTS.router in plan.resolve.alias).toBe(false) }) + // No server takes the request of a client test, so the module that sends + // it is replaced by the one that asks the mocks of `mockServerFn`. + test.each(['react', 'solid', 'vue'] as const)( + 'sends the server function calls of %s client code to the mocks', + (framework) => { + const plan = createViteTestConfigPlan({ + framework, + entryPaths: { ...entryPaths, router: undefined }, + optimizeDepsExclude: [], + noExternal: [], + }) + + expect(plan.resolve.alias).toMatchObject({ + [`@tanstack/${framework}-start/client-rpc`]: `@tanstack/${framework}-start/testing/client-rpc`, + }) + }, + ) + test('keeps the libraries built on Start out of pre-bundling and externalization', () => { const plan = createViteTestConfigPlan({ framework: 'solid', diff --git a/packages/start-plugin-core/tests/vite/test-run.test.ts b/packages/start-plugin-core/tests/vite/test-run.test.ts index edf802dde16..e1c9b2f3b6c 100644 --- a/packages/start-plugin-core/tests/vite/test-run.test.ts +++ b/packages/start-plugin-core/tests/vite/test-run.test.ts @@ -1,7 +1,9 @@ +import { existsSync } from 'node:fs' import { afterEach, describe, expect, test, vi } from 'vitest' import { excludeFromTestRuns, testRunRouterEntryPlugin, + vitestSetupFilePlugin, } from '../../src/vite/test-run' import type { ConfigEnv, Plugin, PluginOption } from 'vite' @@ -124,3 +126,36 @@ describe('testRunRouterEntryPlugin', () => { ) }) }) + +describe('vitestSetupFilePlugin', () => { + type ConfigureVitest = (context: { + project: { config: { setupFiles: Array } } + }) => void + + function configureVitest(isTestRun: boolean, setupFiles: Array) { + const plugin = vitestSetupFilePlugin(() => isTestRun) as Plugin & { + configureVitest: ConfigureVitest + } + plugin.configureVitest({ project: { config: { setupFiles } } }) + } + + test('adds the setup file of Start after the ones of the project, once', () => { + const setupFiles = ['/project/tests/setup.ts'] + + configureVitest(true, setupFiles) + configureVitest(true, setupFiles) + + expect(setupFiles).toHaveLength(2) + expect(setupFiles[0]).toBe('/project/tests/setup.ts') + expect(setupFiles[1]).toMatch(/start-client-core\/.*testing\/vitest\.js$/) + expect(existsSync(setupFiles[1]!)).toBe(true) + }) + + test('leaves a project alone outside of a test run', () => { + const setupFiles: Array = [] + + configureVitest(false, setupFiles) + + expect(setupFiles).toEqual([]) + }) +}) diff --git a/packages/start-server-core/package.json b/packages/start-server-core/package.json index 020747da699..949f89b507b 100644 --- a/packages/start-server-core/package.json +++ b/packages/start-server-core/package.json @@ -88,6 +88,12 @@ "default": "./dist/esm/virtual-modules.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing/index.d.ts", + "default": "./dist/esm/testing/index.js" + } + }, "./package.json": "./package.json" }, "imports": { diff --git a/packages/start-server-core/src/createStartHandler.ts b/packages/start-server-core/src/createStartHandler.ts index f1be8fe0d9a..70878c4fb2f 100644 --- a/packages/start-server-core/src/createStartHandler.ts +++ b/packages/start-server-core/src/createStartHandler.ts @@ -7,7 +7,6 @@ import { csrfSymbol, flattenMiddlewares, mergeHeaders, - safeObjectMerge, } from '@tanstack/start-client-core' import { _getRenderedMatches, @@ -20,7 +19,6 @@ import { bindSsrResponseToRequest, disposeSsrResponse, getNormalizedURL, - isSsrResponse, normalizeSsrResponse, stripSsrResponseBody, waitForRequest, @@ -33,17 +31,19 @@ import { createFinalizedResponse, finalizeResponse, reconcileResponse, - restoreResponseProtocol, transferResponseMetadata, - transferResponseProtocol, withStartRequest, } from './internal-request-response' import { getStartManifest } from './router-manifest' import { - DeferredResponse, + createLateResponseDisposer, + disposeResponseResult, + executeMiddleware, + throwIfMayNotDefer, +} from './request-middleware' +import { createServerFnErrorResponse, handleServerAction, - toThrownServerFnResponse, } from './server-functions-handler' import { createEarlyHintsCollector } from './early-hints' import { @@ -53,6 +53,7 @@ import { import { HEADERS } from './constants' import { ServerFunctionSerializationAdapter } from './serializer/ServerFunctionSerializationAdapter' +import type { DeferredResponse } from './server-functions-handler' import type { AnyFunctionMiddleware, AnyRequestMiddleware, @@ -76,6 +77,7 @@ import type { SsrResponse, } from '@tanstack/router-core/ssr/server' import type { FinalManifestOptions } from './finalManifest' +import type { PipelineContext } from './request-middleware' type TODO = any @@ -189,403 +191,6 @@ const ROUTER_BASEPATH = process.env.TSS_ROUTER_BASEPATH || '/' const SERVER_FN_BASE = process.env.TSS_SERVER_FN_BASE const IS_PRERENDERING = process.env.TSS_PRERENDERING === 'true' const IS_SHELL_ENV = process.env.TSS_SHELL === 'true' -const IS_DEV = process.env.NODE_ENV === 'development' - -// Reusable error messages -const ERR_NO_RESPONSE = IS_DEV - ? `It looks like you forgot to return a response from your server route handler. If you want to defer to the app router, make sure to have a component set in this route.` - : 'Internal Server Error' - -const ERR_NO_DEFER = IS_DEV - ? `You cannot defer to the app router if there is no component defined on this route.` - : 'Internal Server Error' - -function throwRouteHandlerError(): never { - throw new Error(ERR_NO_RESPONSE) -} - -function throwIfMayNotDefer(): never { - throw new Error(ERR_NO_DEFER) -} - -function getResponseFromResult(result: TODO): TODO { - return isSsrResponse(result) || result instanceof Response - ? result - : result?.response -} - -type StreamSsrResponse = Extract - -type ResponseBody = NonNullable -type ResponseWithBody = Response & { readonly body: ResponseBody } - -/** The context object threaded through one middleware pipeline. */ -interface PipelineContext { - request: Request - pathname: string - handlerType: 'serverFn' | 'router' - context: Record - params?: Record - response?: Response - // Middleware may add arbitrary own properties through `next(ctx)`. - [key: string]: unknown -} - -interface MiddlewareResponseOwnership { - response: ResponseWithBody - sourceBody: ResponseBody - streamResponse?: StreamSsrResponse -} - -function disposeResponseResult(result: TODO, reason: unknown): void { - const response = getResponseFromResult(result) - if (isSsrResponse(response) || response instanceof Response) { - disposeSsrResponse(response, reason) - } -} - -/** - * A new body continues the owned one when it is the same stream, or when the - * owned body is already being read, as by a pipe, a tee, or a `Response` that - * copies a body by reading it (Bun, or a wrapped global `Response`). Start - * cannot tell such a reader from one that stops early, so it disposes only an - * unread body. A stream whose reader stops early ends with the request's abort - * or the SSR stream's lifetime limit. - */ -function inheritsResponseOwnership( - ownership: MiddlewareResponseOwnership, - body: ResponseBody, -): boolean { - const ownedBody = ownership.response.body - return body === ownedBody || ownedBody.locked -} - -function disposeResponseOwnership( - ownership: MiddlewareResponseOwnership, - reason: unknown, -): void { - const { response, sourceBody, streamResponse } = ownership - streamResponse?.dispose(reason) - if (!streamResponse || response.body !== sourceBody) { - void response.body.cancel(reason).catch(() => {}) - } -} - -function getOwnedResponse( - ownership: MiddlewareResponseOwnership, -): HandlerCallbackResult { - const { response, sourceBody, streamResponse } = ownership - if (!streamResponse) { - return response - } - if (streamResponse.response === response && response.body === sourceBody) { - return streamResponse - } - if (response.body === sourceBody) { - return { ...streamResponse, response } - } - return { - ...streamResponse, - response, - dispose(reason): undefined { - disposeResponseOwnership(ownership, reason) - }, - } -} - -function createLateResponseDisposer(signal: AbortSignal) { - return (result: TODO) => disposeResponseResult(result, signal.reason) -} - -/** - * Compose middleware around a terminal response handler. With no middleware - * the terminal runs directly. - */ -async function executeMiddleware( - middlewares: Array, - terminal: TODO, - ctx: PipelineContext, - signal: AbortSignal, - event: StartEvent, - terminalNext?: TODO, -): Promise { - let index = -1 - let responseOwnership: MiddlewareResponseOwnership | undefined - // Invocations form one chain: invocation `d` runs middleware `d` and calls - // next() at most once; the pipeline itself is depth -1. Once an invocation - // returns, a result of next() still pending below it is abandoned: it must - // not replace or cancel the response that invocation chose (for example the - // winner of a `Promise.race`). A caller at depth `d` is therefore abandoned - // when `returnedDepth <= d`, where this is the shallowest returned depth. - let returnedDepth = Infinity - const disposeAbandonedResult = createLateResponseDisposer(signal) - - const adoptResponse = ( - exposed: Response | undefined, - streamResponse?: StreamSsrResponse, - ) => { - const current = responseOwnership - // Read the body once: the getter can allocate a stream for a response - // that has not exposed one yet. - const body = exposed instanceof Response ? exposed.body : null - // `exposed` is a Response with this body whenever `body` is set. - const response = exposed as ResponseWithBody - if (streamResponse && !body && streamResponse !== current?.streamResponse) { - streamResponse.dispose('Response body dropped by Start reconciliation') - } - if (current && current.response === exposed) { - current.streamResponse ??= streamResponse - } else if (current && body && inheritsResponseOwnership(current, body)) { - // A wrapper around the same body stream carries the same encoded bytes, - // so it keeps the transport requirements that decode them. - if (body === current.response.body) { - transferResponseProtocol(current.response, response) - } - current.response = response - current.streamResponse ??= streamResponse - } else { - if (current) { - responseOwnership = undefined - disposeResponseOwnership(current, 'middleware response replaced') - } - responseOwnership = body - ? { response, sourceBody: body, streamResponse } - : undefined - } - ctx.response = exposed - } - - const disposeCurrentBody = (reason: string) => { - const current = responseOwnership - responseOwnership = undefined - if (current) { - disposeResponseOwnership(current, reason) - } - } - - const setResponse = (response: TODO, caller: number) => { - // The owned response is already adopted; only helper state can still - // change it. - const owned = - response !== undefined && response === responseOwnership?.response - const ssrResponse = !owned && isSsrResponse(response) ? response : undefined - const exposed: Response | undefined = ssrResponse - ? ssrResponse.response - : response - - if (returnedDepth <= caller) { - if (exposed !== ctx.response) { - disposeResponseResult(response, 'late middleware response') - } - return - } - if (!owned) { - // Dispose a replaced body before reading helper state: cancellation and - // SSR cleanup callbacks may set headers on the response that replaces it. - adoptResponse( - exposed, - ssrResponse?.serverSsrCleanup === 'stream' ? ssrResponse : undefined, - ) - } - if (exposed instanceof Response) { - const reconciled = reconcileResponse(exposed, event, disposeCurrentBody) - if (reconciled !== exposed) { - adoptRebuilt(exposed, reconciled) - } - } - } - - // Start rebuilds the owned response around its body, or without a body when - // the response cannot have one. A rebuilt body takes over ownership without - // comparing streams: a wrapped global `Response` copies it into a new one. - const adoptRebuilt = (exposed: Response, rebuilt: Response) => { - const current = responseOwnership - if (current?.response === exposed && rebuilt.body) { - current.response = rebuilt as ResponseWithBody - ctx.response = rebuilt - } else { - adoptResponse(rebuilt) - } - } - - let nextPromise: Promise | undefined - - function next(nextCtx?: TODO): Promise { - // Only the deepest started invocation can call next(). - const result = runNext(index, nextCtx) - nextPromise = result - return result - } - - async function runNext(caller: number, nextCtx?: TODO): Promise { - signal.throwIfAborted() - - // Merge context if provided using safeObjectMerge for prototype pollution prevention - if (nextCtx) { - if (nextCtx.context) { - ctx.context = safeObjectMerge(ctx.context, nextCtx.context) - } - // Copy own properties except context (Object.keys returns only own - // enumerable properties). An indexed loop avoids the iterator protocol. - const keys = Object.keys(nextCtx) - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (let i = 0; i < keys.length; i++) { - const key = keys[i]! - if (key === 'response') { - setResponse(nextCtx.response, caller) - } else if (key !== 'context') { - ctx[key] = nextCtx[key] - } - } - } - - const depth = ++index - const isTerminal = depth === middlewares.length - const middleware = - depth < middlewares.length - ? middlewares[depth] - : isTerminal - ? terminal - : undefined - const middlewareNext = isTerminal && terminalNext ? terminalNext : next - if (!middleware) { - return ctx - } - - let result: TODO - try { - const pending = middleware({ ...ctx, next: middlewareNext }) - // A directly returned next() promise already propagates request aborts. - if (nextPromise && pending === nextPromise) { - nextPromise = undefined - result = await pending - signal.throwIfAborted() - } else if (!isPromise(pending)) { - result = pending - signal.throwIfAborted() - } else { - result = await waitForRequest( - pending, - signal, - disposeAbandonedResult, - disposeAbandonedResult, - ) - } - } catch (err) { - if (depth < returnedDepth) { - returnedDepth = depth - } - if (returnedDepth > caller) { - // Middleware can replace next()'s shared response before throwing. - // Track that body for cleanup without rebuilding a body it may have - // already locked, consumed, or transferred. - adoptResponse(ctx.response) - } - if (signal.aborted) { - if (result !== undefined) { - disposeAbandonedResult(result) - } - if (err !== signal.reason) { - disposeAbandonedResult(err) - } - throw signal.reason - } - if (err instanceof Response) { - // A thrown Response replies to the request. For a server function - // call, the client rejects the call with it. - setResponse( - ctx.handlerType === 'serverFn' ? toThrownServerFnResponse(err) : err, - caller, - ) - return ctx - } - throw err - } - if (depth < returnedDepth) { - returnedDepth = depth - } - - if (isTerminal && terminalNext && !result) { - throwRouteHandlerError() - } - - if (isTerminal && !terminalNext && result instanceof DeferredResponse) { - if (returnedDepth > caller) { - // Cleanup may write response helpers. Construct only after it has run, - // then publish without rechecking headers that no user has received. - adoptResponse(undefined) - adoptResponse(result.createResponse(event)) - } - return ctx - } - - if (result && result !== ctx) { - const response = getResponseFromResult(result) - // Select the replacement before reconciling: middleware may already - // have transferred or piped the previous response's body. - if (response !== undefined) { - // Middleware can assign next()'s shared response and then return - // another one, such as a 304 after transforming the body. Track the - // assigned body first, so the replacement disposes it, without - // rebuilding a body it may have already locked or consumed. - if ( - ctx.response !== responseOwnership?.response && - ctx.response !== response && - returnedDepth > caller - ) { - adoptResponse(ctx.response) - } - setResponse(response, caller) - } else { - setResponse(ctx.response, caller) - } - if ( - returnedDepth > caller && - response !== result && - result.context && - result.context !== ctx.context - ) { - ctx.context = safeObjectMerge(ctx.context, result.context) - } - } else { - setResponse(ctx.response, caller) - } - - return ctx - } - - try { - await runNext(-1) - let response = ctx.response - if (!response) { - throwRouteHandlerError() - } - if (signal.aborted) { - throw signal.reason - } - returnedDepth = -1 - // Middleware can change protocol headers directly on a server-function - // reply, the only response that has them. Restore them once, as the reply - // leaves the pipeline; without middleware only Start has handled it. - if (middlewares.length && ctx.handlerType === 'serverFn') { - const restored = restoreResponseProtocol(response, event) - if (restored !== response) { - adoptRebuilt(response, restored) - response = restored - } - } - return responseOwnership ? getOwnedResponse(responseOwnership) : response - } catch (err) { - returnedDepth = -1 - if (responseOwnership) { - disposeResponseOwnership( - responseOwnership, - signal.aborted ? signal.reason : err, - ) - } - throw err - } -} /** * Creates the TanStack Start request handler. diff --git a/packages/start-server-core/src/request-middleware.ts b/packages/start-server-core/src/request-middleware.ts new file mode 100644 index 00000000000..5851de07c5e --- /dev/null +++ b/packages/start-server-core/src/request-middleware.ts @@ -0,0 +1,427 @@ +import { safeObjectMerge } from '@tanstack/start-client-core' +import { isPromise } from '@tanstack/router-core' +import { + disposeSsrResponse, + isSsrResponse, + waitForRequest, +} from '@tanstack/router-core/ssr/server' +import { + reconcileResponse, + restoreResponseProtocol, + transferResponseProtocol, +} from './internal-request-response' +import { + DeferredResponse, + toThrownServerFnResponse, +} from './server-functions-handler' +import type { StartEvent } from './internal-request-response' +import type { + HandlerCallbackResult, + SsrResponse, +} from '@tanstack/router-core/ssr/server' + +/** + * The request middleware pipeline of the Start handler: it runs middleware + * around a terminal handler and owns the response they pass along. Kept in + * a module of its own so that the test helpers run the same pipeline. + */ + +type TODO = any + +const IS_DEV = process.env.NODE_ENV === 'development' + +// Reusable error messages +const ERR_NO_RESPONSE = IS_DEV + ? `It looks like you forgot to return a response from your server route handler. If you want to defer to the app router, make sure to have a component set in this route.` + : 'Internal Server Error' + +const ERR_NO_DEFER = IS_DEV + ? `You cannot defer to the app router if there is no component defined on this route.` + : 'Internal Server Error' + +export function throwRouteHandlerError(): never { + throw new Error(ERR_NO_RESPONSE) +} + +export function throwIfMayNotDefer(): never { + throw new Error(ERR_NO_DEFER) +} + +export function getResponseFromResult(result: TODO): TODO { + return isSsrResponse(result) || result instanceof Response + ? result + : result?.response +} + +type StreamSsrResponse = Extract + +type ResponseBody = NonNullable +type ResponseWithBody = Response & { readonly body: ResponseBody } + +/** The context object threaded through one middleware pipeline. */ +export interface PipelineContext { + request: Request + pathname: string + handlerType: 'serverFn' | 'router' + context: Record + params?: Record + response?: Response + // Middleware may add arbitrary own properties through `next(ctx)`. + [key: string]: unknown +} + +interface MiddlewareResponseOwnership { + response: ResponseWithBody + sourceBody: ResponseBody + streamResponse?: StreamSsrResponse +} + +export function disposeResponseResult(result: TODO, reason: unknown): void { + const response = getResponseFromResult(result) + if (isSsrResponse(response) || response instanceof Response) { + disposeSsrResponse(response, reason) + } +} + +/** + * A new body continues the owned one when it is the same stream, or when the + * owned body is already being read, as by a pipe, a tee, or a `Response` that + * copies a body by reading it (Bun, or a wrapped global `Response`). Start + * cannot tell such a reader from one that stops early, so it disposes only an + * unread body. A stream whose reader stops early ends with the request's abort + * or the SSR stream's lifetime limit. + */ +function inheritsResponseOwnership( + ownership: MiddlewareResponseOwnership, + body: ResponseBody, +): boolean { + const ownedBody = ownership.response.body + return body === ownedBody || ownedBody.locked +} + +function disposeResponseOwnership( + ownership: MiddlewareResponseOwnership, + reason: unknown, +): void { + const { response, sourceBody, streamResponse } = ownership + streamResponse?.dispose(reason) + if (!streamResponse || response.body !== sourceBody) { + void response.body.cancel(reason).catch(() => {}) + } +} + +function getOwnedResponse( + ownership: MiddlewareResponseOwnership, +): HandlerCallbackResult { + const { response, sourceBody, streamResponse } = ownership + if (!streamResponse) { + return response + } + if (streamResponse.response === response && response.body === sourceBody) { + return streamResponse + } + if (response.body === sourceBody) { + return { ...streamResponse, response } + } + return { + ...streamResponse, + response, + dispose(reason): undefined { + disposeResponseOwnership(ownership, reason) + }, + } +} + +export function createLateResponseDisposer(signal: AbortSignal) { + return (result: TODO) => disposeResponseResult(result, signal.reason) +} + +/** + * Compose middleware around a terminal response handler. With no middleware + * the terminal runs directly. + */ +export async function executeMiddleware( + middlewares: Array, + terminal: TODO, + ctx: PipelineContext, + signal: AbortSignal, + event: StartEvent, + terminalNext?: TODO, +): Promise { + let index = -1 + let responseOwnership: MiddlewareResponseOwnership | undefined + // Invocations form one chain: invocation `d` runs middleware `d` and calls + // next() at most once; the pipeline itself is depth -1. Once an invocation + // returns, a result of next() still pending below it is abandoned: it must + // not replace or cancel the response that invocation chose (for example the + // winner of a `Promise.race`). A caller at depth `d` is therefore abandoned + // when `returnedDepth <= d`, where this is the shallowest returned depth. + let returnedDepth = Infinity + const disposeAbandonedResult = createLateResponseDisposer(signal) + + const adoptResponse = ( + exposed: Response | undefined, + streamResponse?: StreamSsrResponse, + ) => { + const current = responseOwnership + // Read the body once: the getter can allocate a stream for a response + // that has not exposed one yet. + const body = exposed instanceof Response ? exposed.body : null + // `exposed` is a Response with this body whenever `body` is set. + const response = exposed as ResponseWithBody + if (streamResponse && !body && streamResponse !== current?.streamResponse) { + streamResponse.dispose('Response body dropped by Start reconciliation') + } + if (current && current.response === exposed) { + current.streamResponse ??= streamResponse + } else if (current && body && inheritsResponseOwnership(current, body)) { + // A wrapper around the same body stream carries the same encoded bytes, + // so it keeps the transport requirements that decode them. + if (body === current.response.body) { + transferResponseProtocol(current.response, response) + } + current.response = response + current.streamResponse ??= streamResponse + } else { + if (current) { + responseOwnership = undefined + disposeResponseOwnership(current, 'middleware response replaced') + } + responseOwnership = body + ? { response, sourceBody: body, streamResponse } + : undefined + } + ctx.response = exposed + } + + const disposeCurrentBody = (reason: string) => { + const current = responseOwnership + responseOwnership = undefined + if (current) { + disposeResponseOwnership(current, reason) + } + } + + const setResponse = (response: TODO, caller: number) => { + // The owned response is already adopted; only helper state can still + // change it. + const owned = + response !== undefined && response === responseOwnership?.response + const ssrResponse = !owned && isSsrResponse(response) ? response : undefined + const exposed: Response | undefined = ssrResponse + ? ssrResponse.response + : response + + if (returnedDepth <= caller) { + if (exposed !== ctx.response) { + disposeResponseResult(response, 'late middleware response') + } + return + } + if (!owned) { + // Dispose a replaced body before reading helper state: cancellation and + // SSR cleanup callbacks may set headers on the response that replaces it. + adoptResponse( + exposed, + ssrResponse?.serverSsrCleanup === 'stream' ? ssrResponse : undefined, + ) + } + if (exposed instanceof Response) { + const reconciled = reconcileResponse(exposed, event, disposeCurrentBody) + if (reconciled !== exposed) { + adoptRebuilt(exposed, reconciled) + } + } + } + + // Start rebuilds the owned response around its body, or without a body when + // the response cannot have one. A rebuilt body takes over ownership without + // comparing streams: a wrapped global `Response` copies it into a new one. + const adoptRebuilt = (exposed: Response, rebuilt: Response) => { + const current = responseOwnership + if (current?.response === exposed && rebuilt.body) { + current.response = rebuilt as ResponseWithBody + ctx.response = rebuilt + } else { + adoptResponse(rebuilt) + } + } + + let nextPromise: Promise | undefined + + function next(nextCtx?: TODO): Promise { + // Only the deepest started invocation can call next(). + const result = runNext(index, nextCtx) + nextPromise = result + return result + } + + async function runNext(caller: number, nextCtx?: TODO): Promise { + signal.throwIfAborted() + + // Merge context if provided using safeObjectMerge for prototype pollution prevention + if (nextCtx) { + if (nextCtx.context) { + ctx.context = safeObjectMerge(ctx.context, nextCtx.context) + } + // Copy own properties except context (Object.keys returns only own + // enumerable properties). An indexed loop avoids the iterator protocol. + const keys = Object.keys(nextCtx) + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (let i = 0; i < keys.length; i++) { + const key = keys[i]! + if (key === 'response') { + setResponse(nextCtx.response, caller) + } else if (key !== 'context') { + ctx[key] = nextCtx[key] + } + } + } + + const depth = ++index + const isTerminal = depth === middlewares.length + const middleware = + depth < middlewares.length + ? middlewares[depth] + : isTerminal + ? terminal + : undefined + const middlewareNext = isTerminal && terminalNext ? terminalNext : next + if (!middleware) { + return ctx + } + + let result: TODO + try { + const pending = middleware({ ...ctx, next: middlewareNext }) + // A directly returned next() promise already propagates request aborts. + if (nextPromise && pending === nextPromise) { + nextPromise = undefined + result = await pending + signal.throwIfAborted() + } else if (!isPromise(pending)) { + result = pending + signal.throwIfAborted() + } else { + result = await waitForRequest( + pending, + signal, + disposeAbandonedResult, + disposeAbandonedResult, + ) + } + } catch (err) { + if (depth < returnedDepth) { + returnedDepth = depth + } + if (returnedDepth > caller) { + // Middleware can replace next()'s shared response before throwing. + // Track that body for cleanup without rebuilding a body it may have + // already locked, consumed, or transferred. + adoptResponse(ctx.response) + } + if (signal.aborted) { + if (result !== undefined) { + disposeAbandonedResult(result) + } + if (err !== signal.reason) { + disposeAbandonedResult(err) + } + throw signal.reason + } + if (err instanceof Response) { + // A thrown Response replies to the request. For a server function + // call, the client rejects the call with it. + setResponse( + ctx.handlerType === 'serverFn' ? toThrownServerFnResponse(err) : err, + caller, + ) + return ctx + } + throw err + } + if (depth < returnedDepth) { + returnedDepth = depth + } + + if (isTerminal && terminalNext && !result) { + throwRouteHandlerError() + } + + if (isTerminal && !terminalNext && result instanceof DeferredResponse) { + if (returnedDepth > caller) { + // Cleanup may write response helpers. Construct only after it has run, + // then publish without rechecking headers that no user has received. + adoptResponse(undefined) + adoptResponse(result.createResponse(event)) + } + return ctx + } + + if (result && result !== ctx) { + const response = getResponseFromResult(result) + // Select the replacement before reconciling: middleware may already + // have transferred or piped the previous response's body. + if (response !== undefined) { + // Middleware can assign next()'s shared response and then return + // another one, such as a 304 after transforming the body. Track the + // assigned body first, so the replacement disposes it, without + // rebuilding a body it may have already locked or consumed. + if ( + ctx.response !== responseOwnership?.response && + ctx.response !== response && + returnedDepth > caller + ) { + adoptResponse(ctx.response) + } + setResponse(response, caller) + } else { + setResponse(ctx.response, caller) + } + if ( + returnedDepth > caller && + response !== result && + result.context && + result.context !== ctx.context + ) { + ctx.context = safeObjectMerge(ctx.context, result.context) + } + } else { + setResponse(ctx.response, caller) + } + + return ctx + } + + try { + await runNext(-1) + let response = ctx.response + if (!response) { + throwRouteHandlerError() + } + if (signal.aborted) { + throw signal.reason + } + returnedDepth = -1 + // Middleware can change protocol headers directly on a server-function + // reply, the only response that has them. Restore them once, as the reply + // leaves the pipeline; without middleware only Start has handled it. + if (middlewares.length && ctx.handlerType === 'serverFn') { + const restored = restoreResponseProtocol(response, event) + if (restored !== response) { + adoptRebuilt(response, restored) + response = restored + } + } + return responseOwnership ? getOwnedResponse(responseOwnership) : response + } catch (err) { + returnedDepth = -1 + if (responseOwnership) { + disposeResponseOwnership( + responseOwnership, + signal.aborted ? signal.reason : err, + ) + } + throw err + } +} diff --git a/packages/start-server-core/src/testing/index.ts b/packages/start-server-core/src/testing/index.ts new file mode 100644 index 00000000000..ec08ed98a84 --- /dev/null +++ b/packages/start-server-core/src/testing/index.ts @@ -0,0 +1,33 @@ +export { runInRequest } from './runInRequest' +export type { + GlobalMiddlewareContext, + RequestDescription, + RunInRequestOptions, +} from './runInRequest' +export { mockMiddleware } from './middlewareMocks' +export type { + FunctionMiddlewareMockOptions, + MiddlewareMock, + MiddlewareMockNext, + MiddlewareMockNextOptions, + MiddlewareMockResult, + RequestMiddlewareMockOptions, +} from './middlewareMocks' +export { runMiddleware } from './runMiddleware' +export type { + FunctionMiddlewareInput, + FunctionMiddlewarePassed, + FunctionMiddlewareRun, + RequestMiddlewareInput, + RequestMiddlewarePassed, + RequestMiddlewareRun, +} from './runMiddleware' +export type { + AnyMiddleware, + ContextOption, + MiddlewareAddedContext, + MiddlewareInputContext, + MiddlewareMockContext, + MiddlewareOutputContext, + MiddlewareSendContext, +} from './types' diff --git a/packages/start-server-core/src/testing/middlewareMocks.ts b/packages/start-server-core/src/testing/middlewareMocks.ts new file mode 100644 index 00000000000..c9581d5a18d --- /dev/null +++ b/packages/start-server-core/src/testing/middlewareMocks.ts @@ -0,0 +1,197 @@ +import { MockRegistry } from '@tanstack/start-client-core/testing' +import { getScope } from './scope' +import { getMiddlewareType } from './types' +import type { + AnyFunctionMiddleware, + AnyRequestMiddleware, + Method, + ServerFnMeta, +} from '@tanstack/start-client-core' +import type { ActiveMiddlewareMock, MiddlewareMocks } from './scope' +import type { + AnyMiddleware, + ContextOption, + MiddlewareAddedContext, + MiddlewareInputContext, + MiddlewareMockContext, + MiddlewareSendContext, +} from './types' + +/** + * Mocks for middleware in server tests. + * + * `mockMiddleware` swaps the server and the client function of a middleware + * object for dispatchers, once. A dispatcher calls the mock that is active + * for the middleware, or the original function when there is none. Nothing + * of this is in the code an app ships. + */ + +declare const middlewareMockResult: unique symbol + +/** + * What `next()` resolves to in a mock. A mock returns it to let the call go + * on, as a middleware returns the result of its `next()`. + */ +export interface MiddlewareMockResult { + readonly [middlewareMockResult]: true +} + +/** What a mock passes to `next()`: what the mocked middleware passes. */ +export type MiddlewareMockNextOptions = + ContextOption> & + (TMiddleware extends AnyFunctionMiddleware + ? { sendContext?: MiddlewareSendContext } + : {}) + +/** + * `next()` of a mock. Its `context` is required when the mocked middleware + * adds context, because the code after it relies on that context. + */ +export type MiddlewareMockNext = + undefined extends MiddlewareAddedContext + ? ( + options?: MiddlewareMockNextOptions, + ) => Promise + : ( + options: MiddlewareMockNextOptions, + ) => Promise + +/** What the mock of a function middleware gets: what the middleware gets. */ +export interface FunctionMiddlewareMockOptions< + TMiddleware extends AnyFunctionMiddleware, +> { + data: TMiddleware['~types']['allOutput'] + /** Without what the middleware's own client function sends: it does not run. */ + context: MiddlewareMockContext + next: MiddlewareMockNext + method: Method + serverFnMeta: ServerFnMeta +} + +/** What the mock of a request middleware gets: what the middleware gets. */ +export interface RequestMiddlewareMockOptions< + TMiddleware extends AnyRequestMiddleware, +> { + request: Request + pathname: string + context: MiddlewareInputContext + next: MiddlewareMockNext + handlerType: 'serverFn' | 'router' + serverFnMeta?: ServerFnMeta +} + +/** + * Stands for the server function of a middleware. It gets what the + * middleware gets. It goes on by returning `next()`, with the context the + * middleware adds, or it ends the call the way the middleware can: by + * throwing, or (a request middleware) by returning a `Response`. + */ +export type MiddlewareMock = + TMiddleware extends AnyFunctionMiddleware + ? ( + options: FunctionMiddlewareMockOptions, + ) => MiddlewareMockResult | Promise + : TMiddleware extends AnyRequestMiddleware + ? ( + options: RequestMiddlewareMockOptions, + ) => + | MiddlewareMockResult + | Response + | Promise + : never + +type AnyFn = (...args: Array) => any + +/** The mocks registered outside a request scope: of a test, or of the file. */ +const testMocks = new MockRegistry() +/** The functions a middleware had before its dispatchers went in. */ +const originals = new WeakMap< + AnyMiddleware, + { server?: AnyFn; client?: AnyFn } +>() + +function activeMock( + middleware: AnyMiddleware, +): ActiveMiddlewareMock | undefined { + return getScope()?.mocks.get(middleware) ?? testMocks.get(middleware) +} + +function installDispatchers(middleware: AnyMiddleware) { + if (originals.has(middleware)) { + return + } + const options = middleware.options as { server?: AnyFn; client?: AnyFn } + const original = { server: options.server, client: options.client } + originals.set(middleware, original) + + options.server = (serverOptions) => { + const active = activeMock(middleware) + if (active) { + active.ran = true + return active.mock(serverOptions) + } + return original.server + ? original.server(serverOptions) + : serverOptions.next() + } + // A mocked middleware is out of the way as a whole. On the server a call + // runs the client function first, and that function can need a browser. + const client = original.client + if (client) { + options.client = (clientOptions) => + activeMock(middleware) ? clientOptions.next() : client(clientOptions) + } +} + +/** + * Replaces a middleware in server tests. The mock is typed from the + * middleware: it gets what the middleware's server function gets, and it + * passes on the context that function passes on. While a middleware is + * mocked, its client function does not run either. + * + * A mock registered inside `runInRequest` belongs to that request: it wins + * over a mock of the test, ends with the request, and the request fails when + * the mock never ran. A mock registered in a test or in `beforeEach` ends + * with the test. One registered at the top of the file or in `beforeAll` + * stays for the file. + */ +export function mockMiddleware( + middleware: TMiddleware, + mock: MiddlewareMock, +): void { + if (!getMiddlewareType(middleware)) { + throw new Error( + 'mockMiddleware() needs a middleware created with createMiddleware().', + ) + } + installDispatchers(middleware) + ;(getScope()?.mocks ?? testMocks).set(middleware, { + mock: mock as AnyFn, + ran: false, + neverRan: new Error( + 'A middleware was mocked inside runInRequest() and did not run in that request. Either nothing in the request used it after the mock was registered ' + + '(the request middleware of src/start.ts has run before the callback starts: mock it before runInRequest()), ' + + 'or the server ran another copy of it: the server loads the file of a server function a second time, ' + + 'so a middleware that is created in that file exists twice. Create the middleware in a file of its own to mock it.', + ), + }) +} + +/** The server function a middleware was created with, mocked or not. */ +export function getOriginalServerFn( + middleware: AnyMiddleware, +): AnyFn | undefined { + const original = originals.get(middleware) + return original + ? original.server + : (middleware.options as { server?: AnyFn }).server +} + +/** Throws for a mock of a request scope that never ran. */ +export function assertMocksRan(mocks: MiddlewareMocks): void { + for (const active of mocks.values()) { + if (!active.ran) { + throw active.neverRan + } + } +} diff --git a/packages/start-server-core/src/testing/runInRequest.ts b/packages/start-server-core/src/testing/runInRequest.ts new file mode 100644 index 00000000000..b51ff763260 --- /dev/null +++ b/packages/start-server-core/src/testing/runInRequest.ts @@ -0,0 +1,295 @@ +import { createServerHistory } from '@tanstack/history' +import { getNormalizedURL } from '@tanstack/router-core/ssr/server' +import { + createNullProtoObject, + flattenMiddlewares, +} from '@tanstack/start-client-core' +import { runWithStartContext } from '@tanstack/start-storage-context' +import { withStartRequest } from '../internal-request-response' +import { executeMiddleware, getResponseFromResult } from '../request-middleware' +import { assertMocksRan } from './middlewareMocks' +import { runWithScope } from './scope' +import type { AnyRouter, Expand, Register } from '@tanstack/router-core' +import type { + AnyRequestMiddleware, + AnyStartInstanceOptions, + AssignAllServerFnContext, + RouterEntry, + StartEntry, +} from '@tanstack/start-client-core' +import type { StartEvent } from '../internal-request-response' +import type { PipelineContext } from '../request-middleware' +import type { RequestOptions } from '../request-handler' +import type { TestRequestScope } from './scope' +import type { ContextOption } from './types' + +/** The request of a scope: a `Request`, or the parts to build one from. */ +export type RequestDescription = + | { request: Request; url?: never; method?: never; headers?: never } + | { + request?: never + /** Relative URLs are resolved against `http://localhost`. */ + url?: string | URL + method?: string + headers?: HeadersInit + } + +/** + * The context the global middleware of `src/start.ts` leaves for a server + * function: what the server entry passes in, and what the request middleware + * and the function middleware of the start instance add. + */ +export type GlobalMiddlewareContext = Expand< + AssignAllServerFnContext +> + +export type RunInRequestOptions = RequestDescription & + ( + | ({ + globalMiddleware?: undefined + // The request context the server entry passes to Start, see + // `Register['server']['requestContext']`. + } & Pick, 'context'>) + | ({ + /** + * Leaves out the middleware of `src/start.ts`, the request list and + * the function list. `context` then stands for what they pass on. + */ + globalMiddleware: 'skip' + } & ContextOption) + ) + +type AnyFn = (...args: Array) => any + +const NO_ROUTER = + 'This project has no router entry (src/router.tsx), so there is no router to return in a test.' + +async function loadRouter( + url: URL, + startOptions: AnyStartInstanceOptions, +): Promise { + // @ts-ignore The virtual entry is resolved by the bundler, as in createStartHandler. + const routerEntry: RouterEntry = await import('#tanstack-router-entry') + // (the placeholder entry of a project without a router returns nothing) + const router = (await routerEntry.getRouter()) as AnyRouter | undefined + if (!router) { + throw new Error(NO_ROUTER) + } + // As createStartHandler prepares the router of a request. + router.update({ + history: createServerHistory(url.pathname + url.search + url.hash), + origin: router.options.origin ?? url.origin, + basepath: process.env.TSS_ROUTER_BASEPATH || '/', + ...{ defaultSsr: startOptions.defaultSsr }, + }) + return router +} + +async function runScope( + event: StartEvent, + options: RunInRequestOptions, + callback: () => TResult | Promise, +): Promise { + const request = event.request + const url = getNormalizedURL(event.requestUrl).url + + // @ts-ignore The virtual entry is resolved by the bundler, as in createStartHandler. + const startEntry: StartEntry = await import('#tanstack-start-entry') + const appStartOptions: AnyStartInstanceOptions = + (await startEntry.startInstance?.getOptions()) ?? + ({} as AnyStartInstanceOptions) + const startOptions: AnyStartInstanceOptions = + options.globalMiddleware === 'skip' + ? { + ...appStartOptions, + requestMiddleware: undefined, + functionMiddleware: undefined, + } + : appStartOptions + + // The same set a request of the app keeps: a server function does not run + // a request middleware again that already ran for the request. + const executedRequestMiddlewares = new Set() + const requestMiddleware = flattenMiddlewares( + [...(startOptions.requestMiddleware ?? [])], + undefined, + executedRequestMiddlewares, + ) + + let routerPromise: Promise | undefined + const scope: TestRequestScope = { + request, + pathname: url.pathname, + mocks: new Map(), + } + // Set once the last request middleware lets the request through. + let callbackRun: Promise | undefined + const terminal = async (pipeline: PipelineContext) => { + callbackRun = (async () => + runWithStartContext( + { + getRouter: () => (routerPromise ??= loadRouter(url, startOptions)), + request, + startOptions, + contextAfterGlobalMiddlewares: pipeline.context, + executedRequestMiddlewares, + handlerType: 'router', + }, + callback, + ))() + await callbackRun + // (the pipeline puts what the callback set through the helpers on it) + return new Response(null) + } + + // What next() returned to a middleware, which may not wait for it. + const pendingNext = new Set>() + const middlewares = requestMiddleware.map((middleware) => { + const server = middleware.options.server as + | ((options: PipelineContext & { next: AnyFn }) => unknown) + | undefined + return ( + server && + ((options: PipelineContext & { next: AnyFn }) => + server({ + ...options, + next: (nextOptions?: unknown) => { + const pending = options.next(nextOptions) + pendingNext.add(pending) + // (the callback's error is reported by the scope, so a + // middleware that does not wait for it gets no unhandled rejection) + pending.catch(() => {}) + return pending + }, + })) + ) + }) + + /** Waits until no middleware waits for a call of next() any more. */ + const settlePendingNext = async () => { + let firstError: { error: unknown } | undefined + while (pendingNext.size) { + const batch = [...pendingNext] + pendingNext.clear() + for (const settled of await Promise.allSettled(batch)) { + if (settled.status === 'rejected') { + firstError ??= { error: settled.reason } + } + } + } + return firstError + } + + return runWithScope(scope, async () => { + let result: unknown + let pipelineError: { error: unknown } | undefined + try { + // The request middleware pipeline of the app. + result = await executeMiddleware( + middlewares, + terminal, + { + request, + pathname: url.pathname, + handlerType: 'router', + context: createNullProtoObject( + options.context as Record | undefined, + ), + }, + request.signal, + event, + ) + } catch (error) { + pipelineError = { error } + } + // A middleware that did not wait for next() may still lead to the + // callback, through a middleware after it that calls next() later. + const pendingError = await settlePendingNext() + try { + if (!callbackRun) { + const error = pipelineError ?? pendingError + if (error) { + throw error.error + } + const response = getResponseFromResult(result) as Response | undefined + throw new Error( + `runInRequest(): a request middleware of src/start.ts ended the request${ + response ? ` with status ${response.status}` : '' + } before the callback ran. ` + + `Send a request the middleware lets through, replace the middleware with mockMiddleware(), or pass globalMiddleware: 'skip'. ` + + `To test the middleware itself, call it with runMiddleware().`, + { cause: response }, + ) + } + // The callback is what the test is about: its error wins over what a + // middleware made of it. + const value = await callbackRun + if (pipelineError) { + throw pipelineError.error + } + assertMocksRan(scope.mocks) + return value + } finally { + // Mocks of the request end with it, also for work it left running. + scope.closed = true + } + }) +} + +function toRequest(options: RunInRequestOptions): Request { + if (options.request) { + return options.request + } + return new Request(new URL(options.url ?? '/', 'http://localhost'), { + method: options.method, + headers: options.headers, + }) +} + +/** + * Runs `callback` as code that handles one request to the app's server. + * + * The global request middleware of `src/start.ts` runs first. Inside the + * callback a server function can be called as a loader calls it while the + * server renders a page: its client middleware runs, then its server + * middleware, its validator and its handler. Start's request and response + * helpers (`getRequest`, `getCookie`, `setResponseHeader`, + * `getResponseHeader`, ...) work inside the callback as well. + * + * Resolves to what the callback returns, and rejects with what it throws. + */ +export function runInRequest( + callback: {} extends RunInRequestOptions + ? () => TResult | Promise + : never, +): Promise +export function runInRequest( + options: RunInRequestOptions, + callback: () => TResult | Promise, +): Promise +export async function runInRequest( + ...args: + | [callback: () => TResult | Promise] + | [options: RunInRequestOptions, callback: () => TResult | Promise] +): Promise { + const [options, callback] = args.length === 1 ? [{}, args[0]] : args + if (typeof callback !== 'function') { + throw new Error( + 'runInRequest() needs a callback: runInRequest(options, async () => { ... }).', + ) + } + const request = toRequest(options) + let result: Promise | undefined + const handleRequest = withStartRequest(async (_request, _options, event) => { + result = runScope(event, options, callback) + await result + return new Response(null) + }) + const response = await handleRequest(request, undefined) + if (!result) { + throw new Error( + `runInRequest(): Start does not accept the URL of the request, ${request.url} (status ${response.status}).`, + ) + } + return result +} diff --git a/packages/start-server-core/src/testing/runMiddleware.ts b/packages/start-server-core/src/testing/runMiddleware.ts new file mode 100644 index 00000000000..094dc72e9bd --- /dev/null +++ b/packages/start-server-core/src/testing/runMiddleware.ts @@ -0,0 +1,245 @@ +import { + createNullProtoObject, + safeObjectMerge, +} from '@tanstack/start-client-core' +import { getStartEvent } from '../internal-request-response' +import { executeMiddleware, getResponseFromResult } from '../request-middleware' +import { getOriginalServerFn } from './middlewareMocks' +import { getScope } from './scope' +import { getMiddlewareType } from './types' +import type { + AnyFunctionMiddleware, + AnyRequestMiddleware, + Method, + ServerFnMeta, +} from '@tanstack/start-client-core' +import type { PipelineContext } from '../request-middleware' +import type { TestRequestScope } from './scope' +import type { + AnyMiddleware, + ContextOption, + MiddlewareInputContext, + MiddlewareOutputContext, + MiddlewareSendContext, +} from './types' + +type DataOption = undefined extends TData + ? { data?: TData } + : { data: TData } + +/** What a function middleware's server function is called with. */ +export type FunctionMiddlewareInput = + DataOption & + ContextOption> & { + /** Defaults to `GET`. */ + method?: Method + serverFnMeta?: ServerFnMeta + } + +/** What a function middleware passed to `next()`. */ +export interface FunctionMiddlewarePassed< + TMiddleware extends AnyFunctionMiddleware, +> { + /** The context the middleware received, with what it added. */ + context: MiddlewareOutputContext + /** What the middleware sends back to the client. */ + sendContext: MiddlewareSendContext +} + +/** How a function middleware's server function ended. */ +export interface FunctionMiddlewareRun< + TMiddleware extends AnyFunctionMiddleware, + TResult, +> extends FunctionMiddlewarePassed { + /** What the `next` callback of the test returned. */ + result: TResult +} + +/** What a request middleware's server function is called with. */ +export type RequestMiddlewareInput = + ContextOption> & { + /** Defaults to `router`, a request for a page. */ + handlerType?: 'router' | 'serverFn' + serverFnMeta?: ServerFnMeta + } + +/** What a request middleware passed to `next()`. */ +export interface RequestMiddlewarePassed< + TMiddleware extends AnyRequestMiddleware, +> { + /** The context the middleware received, with what it added. */ + context: MiddlewareOutputContext + request: Request + pathname: string +} + +/** How a request middleware's server function ended. */ +export interface RequestMiddlewareRun< + TMiddleware extends AnyRequestMiddleware, +> { + /** + * The context the middleware passed on. It is the context the middleware + * received when the middleware did not call `next()`. + */ + context: MiddlewareOutputContext + /** + * The response the middleware answers the request with: its own, or the + * one that came back from `next()`. + */ + response: Response +} + +type AnyFn = (...args: Array) => any + +const defaultServerFnMeta: ServerFnMeta = { + id: 'runMiddleware', + name: 'runMiddleware', + filename: 'runMiddleware', +} + +async function runFunctionMiddleware( + scope: TestRequestScope, + server: AnyFn, + input: { + data?: unknown + context?: Record + method?: Method + serverFnMeta?: ServerFnMeta + }, + next: AnyFn | undefined, +) { + const options = { + data: input.data, + context: createNullProtoObject(input.context), + method: input.method ?? 'GET', + serverFnMeta: input.serverFnMeta ?? defaultServerFnMeta, + request: scope.request, + } + const returned = await server({ + ...options, + next: async ( + nextOptions: { + context?: Record + sendContext?: unknown + } = {}, + ) => { + const context = safeObjectMerge(options.context, nextOptions.context) + const sendContext = nextOptions.sendContext + const result = await next?.({ context, sendContext }) + return { ...options, ...nextOptions, context, sendContext, result } + }, + }) + + if (returned instanceof Response) { + return { + context: options.context, + sendContext: undefined, + result: returned, + } + } + if (!returned) { + throw new Error( + 'runMiddleware(): the middleware returned nothing. A middleware returns the result of next().', + ) + } + return { + context: returned.context, + sendContext: returned.sendContext, + result: returned.result, + } +} + +async function runRequestMiddleware( + scope: TestRequestScope, + server: AnyFn, + input: { + context?: Record + handlerType?: 'router' | 'serverFn' + serverFnMeta?: ServerFnMeta + }, + next: AnyFn | undefined, +) { + const { request, pathname } = scope + const pipeline: PipelineContext = { + request, + pathname, + handlerType: input.handlerType ?? 'router', + serverFnMeta: input.serverFnMeta, + context: createNullProtoObject(input.context), + } + // The request middleware pipeline of the app, with the middleware alone and + // the test's `next` in place of everything after it. + const result = await executeMiddleware( + [server], + async ({ context }: PipelineContext) => { + const response: unknown = await next?.({ context, request, pathname }) + return response instanceof Response ? response : new Response(null) + }, + pipeline, + request.signal, + getStartEvent(), + ) + return { + context: pipeline.context, + response: getResponseFromResult(result) as Response, + } +} + +/** + * Calls the server function of one middleware, and nothing else: not the + * middleware it lists itself, not its validator, not its client function. + * Use it inside `runInRequest`, which provides the request. + * + * `input` is what the middleware receives: for a function middleware the + * validated `data` and the `context` of the middleware before it, for a + * request middleware the `context`. + * + * `next` stands for everything after the middleware. It gets what the + * middleware passed on. What it returns is the result of the call for a + * function middleware, and the response of the request for a request + * middleware. + */ +export function runMiddleware< + TMiddleware extends AnyFunctionMiddleware, + TResult = undefined, +>( + middleware: TMiddleware, + input: FunctionMiddlewareInput, + next?: ( + passed: FunctionMiddlewarePassed, + ) => TResult | Promise, +): Promise> +export function runMiddleware( + middleware: TMiddleware, + input: RequestMiddlewareInput, + next?: ( + passed: RequestMiddlewarePassed, + ) => Response | void | Promise, +): Promise> +export async function runMiddleware( + middleware: AnyMiddleware, + input: Record, + next?: AnyFn, +): Promise { + const type = getMiddlewareType(middleware) + if (!type) { + throw new Error( + 'runMiddleware() needs a middleware created with createMiddleware().', + ) + } + const scope = getScope() + if (!scope) { + throw new Error( + 'runMiddleware() has to be called inside runInRequest(), which provides the request the middleware runs for.', + ) + } + const server = getOriginalServerFn(middleware) + if (!server) { + throw new Error( + 'runMiddleware(): the middleware has no server function. Only a function passed to .server() can be run.', + ) + } + return type === 'function' + ? runFunctionMiddleware(scope, server, input, next) + : runRequestMiddleware(scope, server, input, next) +} diff --git a/packages/start-server-core/src/testing/scope.ts b/packages/start-server-core/src/testing/scope.ts new file mode 100644 index 00000000000..291e290a540 --- /dev/null +++ b/packages/start-server-core/src/testing/scope.ts @@ -0,0 +1,36 @@ +import { AsyncLocalStorage } from 'node:async_hooks' +import type { AnyMiddleware } from './types' + +type AnyFn = (...args: Array) => any + +/** A mock that `mockMiddleware` registered. */ +export interface ActiveMiddlewareMock { + mock: AnyFn + ran: boolean + /** Created where the mock was registered, so its stack points there. */ + neverRan: Error +} + +export type MiddlewareMocks = Map + +/** What the helpers of a test share while `runInRequest` runs. */ +export interface TestRequestScope { + request: Request + pathname: string + /** The mocks registered inside this scope. They end with it. */ + mocks: MiddlewareMocks + /** Set when `runInRequest` has settled. */ + closed?: boolean +} + +const scopes = new AsyncLocalStorage() + +export function runWithScope(scope: TestRequestScope, fn: () => T): T { + return scopes.run(scope, fn) +} + +/** The request scope that code runs in, until `runInRequest` settles. */ +export function getScope(): TestRequestScope | undefined { + const scope = scopes.getStore() + return scope?.closed ? undefined : scope +} diff --git a/packages/start-server-core/src/testing/types.ts b/packages/start-server-core/src/testing/types.ts new file mode 100644 index 00000000000..e241bd652ce --- /dev/null +++ b/packages/start-server-core/src/testing/types.ts @@ -0,0 +1,86 @@ +import type { + AnyFunctionMiddleware, + AnyRequestMiddleware, + AssignAllServerFnContext, + AssignAllServerRequestContext, + FunctionMiddlewareWithTypes, + RequestMiddlewareWithTypes, +} from '@tanstack/start-client-core' +import type { Expand } from '@tanstack/router-core' + +export type AnyMiddleware = AnyFunctionMiddleware | AnyRequestMiddleware + +/** + * The context a middleware's server function receives: what the server entry, + * the global middleware and the middleware before it passed on. + */ +export type MiddlewareInputContext = + TMiddleware extends FunctionMiddlewareWithTypes< + infer TRegister, + infer TMiddlewares, + any, + any, + infer TServerSendContext, + any, + any + > + ? Expand< + AssignAllServerFnContext + > + : TMiddleware extends RequestMiddlewareWithTypes< + infer TRegister, + infer TMiddlewares, + any + > + ? Expand> + : never + +/** + * The context the mock of a middleware receives: what the middleware's + * server function receives, without what its own client function sends. A + * mocked middleware's client function does not run. + */ +export type MiddlewareMockContext = + TMiddleware extends FunctionMiddlewareWithTypes< + infer TRegister, + infer TMiddlewares, + any, + any, + any, + any, + any + > + ? Expand> + : MiddlewareInputContext + +/** The context a middleware's server function passes to `next()`. */ +export type MiddlewareAddedContext = + TMiddleware['~types']['serverContext'] + +/** The context after a middleware: what it received and what it added. */ +export type MiddlewareOutputContext = Expand< + TMiddleware['~types']['allServerContext'] +> + +/** What a function middleware's server function sends back to the client. */ +export type MiddlewareSendContext = + TMiddleware['~types']['clientSendContext'] + +/** `{ context }`, required when the context has a required property. */ +export type ContextOption = undefined extends TContext + ? { context?: TContext } + : {} extends TContext + ? { context?: TContext } + : { context: TContext } + +/** + * The kind of a middleware, read from the object at runtime. The types of a + * middleware do not declare `options.type`. + */ +export function getMiddlewareType( + middleware: unknown, +): 'function' | 'request' | undefined { + const type = (middleware as { options?: { type?: unknown } } | undefined) + ?.options?.type + return type === 'function' || type === 'request' ? type : undefined +} diff --git a/packages/start-server-core/tests/testing.test-d.ts b/packages/start-server-core/tests/testing.test-d.ts new file mode 100644 index 00000000000..fd567956154 --- /dev/null +++ b/packages/start-server-core/tests/testing.test-d.ts @@ -0,0 +1,207 @@ +import { expectTypeOf, test } from 'vitest' +import { createMiddleware } from '@tanstack/start-client-core' +import { mockMiddleware, runInRequest, runMiddleware } from '../src/testing' +import type { + FunctionMiddlewareRun, + MiddlewareMockResult, + RequestMiddlewareRun, +} from '../src/testing' + +// The functions below are only type-checked. This file also runs as a test +// file, and nothing in it may call the harness. + +const auth = createMiddleware({ type: 'function' }) + .validator((input: { token: string }) => input) + .server(({ next }) => next({ context: { user: { name: 'Ada' } } })) + +const greeting = createMiddleware({ type: 'function' }) + .middleware([auth]) + .server(({ next, context }) => + next({ context: { greeting: `Hello ${context.user.name}` } }), + ) + +const logging = createMiddleware({ type: 'function' }).server(({ next }) => + next(), +) + +const tenant = createMiddleware().server(({ next }) => + next({ context: { tenant: 'acme' } }), +) + +function checkRunInRequest() { + expectTypeOf(runInRequest(() => 5)).toEqualTypeOf>() + expectTypeOf(runInRequest(async () => 'a')).toEqualTypeOf>() + expectTypeOf( + runInRequest({ url: '/posts', headers: { cookie: 'a=b' } }, async () => ({ + ok: true, + })), + ).toEqualTypeOf>() + + void runInRequest({ request: new Request('http://localhost/') }, () => {}) + void runInRequest({ globalMiddleware: 'skip' }, () => {}) + + void runInRequest( + // @ts-expect-error a Request already has a URL + { request: new Request('http://localhost/'), url: '/posts' }, + () => {}, + ) + // @ts-expect-error the only value is 'skip' + void runInRequest({ globalMiddleware: 'run' }, () => {}) + // @ts-expect-error the callback is missing + void runInRequest({ url: '/posts' }) +} + +function checkMockOfFunctionMiddleware() { + mockMiddleware(auth, ({ data, context, method, next }) => { + expectTypeOf(data).toEqualTypeOf<{ token: string }>() + expectTypeOf(context).toEqualTypeOf() + expectTypeOf(method).toEqualTypeOf<'GET' | 'POST'>() + expectTypeOf(next).returns.toEqualTypeOf>() + return next({ context: { user: { name: 'Grace' } } }) + }) + mockMiddleware(auth, async ({ next }) => + next({ context: { user: { name: 'Grace' } } }), + ) + mockMiddleware(auth, () => { + throw new Error('not signed in') + }) + + // @ts-expect-error the middleware passes a user on, so the mock has to + mockMiddleware(auth, ({ next }) => next()) + mockMiddleware(auth, ({ next }) => + // @ts-expect-error the name of the user is a string + next({ context: { user: { name: 5 } } }), + ) + // @ts-expect-error a mock returns the result of next() + mockMiddleware(auth, () => undefined) + // @ts-expect-error a function middleware cannot answer with a response + mockMiddleware(auth, () => new Response(null)) +} + +function checkMockSeesTheContextBeforeTheMiddleware() { + mockMiddleware(greeting, ({ context, next }) => { + expectTypeOf(context).toEqualTypeOf<{ user: { name: string } }>() + return next({ context: { greeting: 'Hi' } }) + }) + mockMiddleware(logging, ({ next }) => next()) +} + +// The client function of a mocked middleware does not run, so what it sends +// to the server is not in the context of the mock. +const withToken = createMiddleware({ type: 'function' }) + .middleware([auth]) + .client(({ next }) => next({ sendContext: { token: 'from the client' } })) + .server(({ next }) => next()) + +function checkMockContextWithoutOwnClientContext() { + mockMiddleware(withToken, ({ context, next }) => { + // (what the middleware before it passes on is still there) + expectTypeOf(context.user).toEqualTypeOf<{ name: string }>() + // @ts-expect-error the client function that sends the token does not run + void context.token + return next() + }) +} + +function checkMockOfRequestMiddleware() { + mockMiddleware(tenant, ({ request, pathname, handlerType, next }) => { + expectTypeOf(request).toEqualTypeOf() + expectTypeOf(pathname).toEqualTypeOf() + expectTypeOf(handlerType).toEqualTypeOf<'serverFn' | 'router'>() + return next({ context: { tenant: 'other' } }) + }) + mockMiddleware(tenant, () => new Response(null, { status: 401 })) + + // @ts-expect-error the middleware passes a tenant on, so the mock has to + mockMiddleware(tenant, ({ next }) => next()) +} + +function checkOnlyMiddlewareCanBeMocked() { + const plain = () => {} + + // @ts-expect-error a plain function is no middleware + mockMiddleware(plain, () => new Response(null)) +} + +async function checkRunOfFunctionMiddleware() { + const run = await runMiddleware( + auth, + { data: { token: 'abc' } }, + ({ context }) => { + expectTypeOf(context).toEqualTypeOf<{ user: { name: string } }>() + return 5 + }, + ) + expectTypeOf(run).toExtend>() + expectTypeOf(run.result).toEqualTypeOf() + expectTypeOf(run.context).toEqualTypeOf<{ user: { name: string } }>() + + const asyncNext = await runMiddleware( + auth, + { data: { token: 'abc' } }, + async () => 'later', + ) + expectTypeOf(asyncNext.result).toEqualTypeOf() + + const withoutNext = await runMiddleware(logging, {}) + expectTypeOf(withoutNext.result).toEqualTypeOf() + + // @ts-expect-error the middleware validates data, so it gets data + void runMiddleware(auth, {}) + // @ts-expect-error the token is a string + void runMiddleware(auth, { data: { token: 5 } }) +} + +async function checkRunNeedsTheContextOfTheMiddlewareBefore() { + const run = await runMiddleware(greeting, { + data: { token: 'abc' }, + context: { user: { name: 'Ada' } }, + }) + expectTypeOf(run.context).toEqualTypeOf<{ + user: { name: string } + greeting: string + }>() + + // @ts-expect-error `auth` runs before it and passes a user on + void runMiddleware(greeting, { data: { token: 'abc' } }) +} + +async function checkRunOfRequestMiddleware() { + const run = await runMiddleware( + tenant, + { handlerType: 'serverFn' }, + ({ context, request, pathname }) => { + expectTypeOf(context).toEqualTypeOf<{ tenant: string }>() + expectTypeOf(request).toEqualTypeOf() + expectTypeOf(pathname).toEqualTypeOf() + return new Response('page') + }, + ) + expectTypeOf(run).toEqualTypeOf>() + expectTypeOf(run.response).toEqualTypeOf() + expectTypeOf(run.context).toEqualTypeOf<{ tenant: string }>() + + void runMiddleware(tenant, {}, () => {}) + // @ts-expect-error the rest of a request answers with a response + void runMiddleware(tenant, {}, () => 'page') + // @ts-expect-error a request middleware gets no data + void runMiddleware(tenant, { data: 'x' }) +} + +test('runInRequest resolves to what the callback returns', () => { + expectTypeOf(checkRunInRequest).toBeFunction() +}) + +test('a mock is typed from the middleware it replaces', () => { + expectTypeOf(checkMockOfFunctionMiddleware).toBeFunction() + expectTypeOf(checkMockSeesTheContextBeforeTheMiddleware).toBeFunction() + expectTypeOf(checkMockOfRequestMiddleware).toBeFunction() + expectTypeOf(checkMockContextWithoutOwnClientContext).toBeFunction() + expectTypeOf(checkOnlyMiddlewareCanBeMocked).toBeFunction() +}) + +test('runMiddleware types the input and the outcome from the middleware', () => { + expectTypeOf(checkRunOfFunctionMiddleware).toBeFunction() + expectTypeOf(checkRunNeedsTheContextOfTheMiddlewareBefore).toBeFunction() + expectTypeOf(checkRunOfRequestMiddleware).toBeFunction() +}) diff --git a/packages/start-server-core/tests/testing.test.ts b/packages/start-server-core/tests/testing.test.ts new file mode 100644 index 00000000000..4ee5d38b040 --- /dev/null +++ b/packages/start-server-core/tests/testing.test.ts @@ -0,0 +1,849 @@ +// @vitest-environment node + +// The setup file Start's plugin adds to a test run: mocks end with the test. +import '@tanstack/start-client-core/testing/vitest' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { createMemoryHistory } from '@tanstack/history' +import { + BaseRootRoute, + RouterCore, + createNonReactiveMutableStore, + createNonReactiveReadonlyStore, +} from '@tanstack/router-core' +import { + createMiddleware, + createServerFn, + getRouterInstance, +} from '@tanstack/start-client-core' +import { createServerRpc } from '../src/createServerRpc' +import { + getCookie, + getRequest, + getResponseHeader, + getResponseStatus, + setResponseHeader, + setResponseStatus, +} from '../src/request-response' +import { mockMiddleware, runInRequest, runMiddleware } from '../src/testing' +import type { AnyRouter } from '@tanstack/router-core' +import type { + AnyFunctionMiddleware, + AnyRequestMiddleware, +} from '@tanstack/start-client-core' + +const app = vi.hoisted(() => ({ + requestMiddleware: [] as Array, + functionMiddleware: [] as Array, + router: undefined as unknown, +})) + +vi.mock('#tanstack-start-entry', () => ({ + startInstance: { + getOptions: () => ({ + requestMiddleware: app.requestMiddleware, + functionMiddleware: app.functionMiddleware, + }), + }, +})) + +vi.mock('#tanstack-router-entry', () => ({ + getRouter: () => app.router, +})) + +function useGlobalMiddleware(options: { + request?: Array + function?: Array +}) { + app.requestMiddleware = options.request ?? [] + app.functionMiddleware = options.function ?? [] + // (registered before anything else of the test can throw) + onTestFinished(() => { + app.requestMiddleware = [] + app.functionMiddleware = [] + }) +} + +type CompiledServerFn = ((opts?: { data?: unknown }) => Promise) & { + __executeServer: (opts: unknown) => Promise +} + +// The compiled shape of a server function in the module that provides it: +// the RPC entry calls the function's server side. +function defineServerFn( + middleware: Array, + handler: (ctx: { data: any; context: any }) => unknown, +): CompiledServerFn { + const attach = createServerFn({ method: 'GET' }).middleware(middleware) + .handler as unknown as (...args: Array) => CompiledServerFn + const rpc = createServerRpc( + { id: 'test', name: 'test', filename: 'test.ts' }, + (opts: unknown) => serverFn.__executeServer(opts), + ) + const serverFn = attach(rpc, handler) + return serverFn +} + +function makeRouter(): AnyRouter { + const router = new RouterCore( + { + history: createMemoryHistory({ initialEntries: ['/'] }), + routeTree: new BaseRootRoute({}), + }, + () => ({ + createMutableStore: createNonReactiveMutableStore, + createReadonlyStore: createNonReactiveReadonlyStore, + batch: (fn: () => void) => fn(), + }), + ) + router.isServer = true + return router +} + +describe('runInRequest', () => { + it('resolves to what the callback returns', async () => { + await expect(runInRequest(() => 'sync')).resolves.toBe('sync') + await expect(runInRequest(async () => 'async')).resolves.toBe('async') + }) + + it('rejects with what the callback throws', async () => { + const error = new Error('from the callback') + + await expect( + runInRequest(() => { + throw error + }), + ).rejects.toBe(error) + }) + + it('sends a GET request to http://localhost/ by default', async () => { + const request = await runInRequest(() => getRequest()) + + expect(request.method).toBe('GET') + expect(request.url).toBe('http://localhost/') + }) + + it('builds the request from url, method and headers', async () => { + await runInRequest( + { + url: '/posts/42?draft=1', + method: 'POST', + headers: { cookie: 'session=abc' }, + }, + () => { + expect(getRequest().url).toBe('http://localhost/posts/42?draft=1') + expect(getRequest().method).toBe('POST') + expect(getCookie('session')).toBe('abc') + }, + ) + }) + + it('takes a Request as it is', async () => { + const request = new Request('https://example.com/a') + + await expect(runInRequest({ request }, () => getRequest())).resolves.toBe( + request, + ) + }) + + it('rejects an aborted request before any middleware or the callback runs', async () => { + const middleware = vi.fn() + useGlobalMiddleware({ request: [createMiddleware().server(middleware)] }) + const controller = new AbortController() + const reason = new Error('the client went away') + controller.abort(reason) + const callback = vi.fn() + + await expect( + runInRequest( + { + request: new Request('http://localhost/', { + signal: controller.signal, + }), + }, + callback, + ), + ).rejects.toBe(reason) + expect(middleware).not.toHaveBeenCalled() + expect(callback).not.toHaveBeenCalled() + }) + + it('lets a test read what a handler set on the response', async () => { + const save = defineServerFn([], () => { + setResponseHeader('cache-control', 'private') + setResponseStatus(201) + return 'saved' + }) + + await runInRequest(async () => { + expect(getResponseHeader('cache-control')).toBeUndefined() + + await expect(save()).resolves.toBe('saved') + + expect(getResponseHeader('cache-control')).toBe('private') + expect(getResponseStatus()).toBe(201) + }) + }) + + it('runs a server function as a loader calls it during server rendering', async () => { + const order: Array = [] + const middleware = createMiddleware({ type: 'function' }) + .client(({ next }) => { + order.push('client') + return next() + }) + .server(({ next }) => { + order.push('server') + return next({ context: { user: 'Ada' } }) + }) + const greet = defineServerFn([middleware], ({ data, context }) => { + order.push('handler') + return `${data} ${context.user}` + }) + + await expect(runInRequest(() => greet({ data: 'Hello' }))).resolves.toBe( + 'Hello Ada', + ) + expect(order).toEqual(['client', 'server', 'handler']) + }) + + it('fails a server function that is called outside of it', async () => { + const greet = defineServerFn([], () => 'hello') + + await expect(greet()).rejects.toThrow( + /No Start context found.*runInRequest\(\)/, + ) + }) + + describe('global middleware', () => { + it('runs the request middleware before the callback and passes its context on', async () => { + const order: Array = [] + useGlobalMiddleware({ + request: [ + createMiddleware().server(async ({ next, context }) => { + order.push('request middleware') + const result = await next({ + context: { + tenant: + (context as unknown as { tenant?: string }).tenant ?? + 'default', + }, + }) + order.push('after') + return result + }), + ], + }) + const readTenant = defineServerFn([], ({ context }) => context.tenant) + + const tenant = await runInRequest( + { context: { tenant: 'acme' } as {} }, + () => { + order.push('callback') + return readTenant() + }, + ) + + expect(tenant).toBe('acme') + expect(order).toEqual(['request middleware', 'callback', 'after']) + }) + + it('runs the function middleware for a server function call', async () => { + useGlobalMiddleware({ + function: [ + createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { locale: 'de' } }), + ), + ], + }) + const readLocale = defineServerFn([], ({ context }) => context.locale) + + await expect(runInRequest(() => readLocale())).resolves.toBe('de') + }) + + it('leaves both lists out with globalMiddleware: skip, and uses the context of the test', async () => { + const requestMiddleware = vi.fn(({ next }) => next()) + const functionMiddleware = vi.fn(({ next }) => next()) + useGlobalMiddleware({ + request: [createMiddleware().server(requestMiddleware)], + function: [ + createMiddleware({ type: 'function' }).server(functionMiddleware), + ], + }) + const readUser = defineServerFn([], ({ context }) => context.user) + + const user = await runInRequest( + { globalMiddleware: 'skip', context: { user: 'Ada' } as never }, + () => readUser(), + ) + + expect(user).toBe('Ada') + expect(requestMiddleware).not.toHaveBeenCalled() + expect(functionMiddleware).not.toHaveBeenCalled() + }) + + it('still runs a global middleware that a server function lists itself, with globalMiddleware: skip', async () => { + const server = vi.fn() + const middleware = createMiddleware({ type: 'function' }).server( + ({ next }) => { + server() + return next() + }, + ) + useGlobalMiddleware({ function: [middleware] }) + const listsIt = defineServerFn([middleware], () => 'done') + const doesNot = defineServerFn([], () => 'done') + + await runInRequest({ globalMiddleware: 'skip' }, () => doesNot()) + expect(server).not.toHaveBeenCalled() + + await runInRequest({ globalMiddleware: 'skip' }, () => listsIt()) + expect(server).toHaveBeenCalledTimes(1) + }) + + it('does not run a request middleware again that a server function lists as well', async () => { + const server = vi.fn(({ next }) => next()) + const middleware = createMiddleware().server(server) + useGlobalMiddleware({ request: [middleware] }) + const fn = defineServerFn([middleware], () => 'done') + + await runInRequest(() => fn()) + + expect(server).toHaveBeenCalledTimes(1) + }) + + it('rejects when a request middleware ends the request before the callback', async () => { + useGlobalMiddleware({ + request: [ + createMiddleware().server(() => new Response(null, { status: 401 })), + ], + }) + const callback = vi.fn() + + const error: Error = await runInRequest(callback).then( + () => { + throw new Error('the scope should have rejected') + }, + (reason) => reason, + ) + + expect(error.message).toMatch( + /ended the request with status 401 before the callback ran/, + ) + expect((error.cause as Response).status).toBe(401) + expect(callback).not.toHaveBeenCalled() + }) + + it('rejects with what a request middleware throws', async () => { + const error = new Error('no session') + useGlobalMiddleware({ + request: [ + createMiddleware().server(() => { + throw error + }), + ], + }) + + await expect(runInRequest(() => 'unreached')).rejects.toBe(error) + }) + + it('rejects with the error of the callback when a middleware turns it into a response', async () => { + const error = new Error('from the callback') + useGlobalMiddleware({ + request: [ + createMiddleware().server(async ({ next }) => { + try { + return await next() + } catch { + return new Response(null, { status: 500 }) + } + }), + ], + }) + + await expect( + runInRequest(() => { + throw error + }), + ).rejects.toBe(error) + }) + + it('waits for the callback when a middleware does not wait for next()', async () => { + useGlobalMiddleware({ + request: [ + createMiddleware().server(({ next }) => { + void next() + return new Response(null) + }), + ], + }) + let finished = false + + const value = await runInRequest(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)) + finished = true + return 'done' + }) + + expect(value).toBe('done') + expect(finished).toBe(true) + }) + + it('gives an outer middleware the response an inner one put on its result', async () => { + let seen: number | undefined + useGlobalMiddleware({ + request: [ + createMiddleware().server(async ({ next }) => { + const result = await next() + seen = result.response.status + return result + }), + createMiddleware().server(async ({ next }) => ({ + ...(await next()), + response: new Response(null, { status: 403 }), + })), + ], + }) + + await runInRequest(() => 'done') + + expect(seen).toBe(403) + }) + + it('gives an outer middleware what an inner one set through the helpers after next()', async () => { + let seen: string | null | undefined + useGlobalMiddleware({ + request: [ + createMiddleware().server(async ({ next }) => { + const result = await next() + seen = result.response.headers.get('x-inner') + return result + }), + createMiddleware().server(async ({ next }) => { + const result = await next() + setResponseHeader('x-inner', 'yes') + return result + }), + ], + }) + + await runInRequest(() => 'done') + + expect(seen).toBe('yes') + }) + + it('waits for an inner middleware that calls next() late, when the outer one does not wait for it', async () => { + useGlobalMiddleware({ + request: [ + createMiddleware().server(({ next }) => { + void next() + return new Response(null) + }), + createMiddleware().server(async ({ next }) => { + await new Promise((resolve) => setTimeout(resolve, 10)) + return next() + }), + ], + }) + + await expect(runInRequest(async () => 'done')).resolves.toBe('done') + + const error = new Error('from the callback') + await expect( + runInRequest(() => { + throw error + }), + ).rejects.toBe(error) + }) + + it('gives a middleware the response with what the callback set through the helpers', async () => { + let seen: Response | undefined + useGlobalMiddleware({ + request: [ + createMiddleware().server(async ({ next }) => { + const result = await next() + seen = result.response + return result + }), + ], + }) + + await runInRequest(() => { + setResponseStatus(404) + setResponseHeader('x-reason', 'missing') + }) + + expect(seen?.status).toBe(404) + expect(seen?.headers.get('x-reason')).toBe('missing') + }) + }) + + describe('getRouterInstance', () => { + it('returns the router of the router entry at the URL of the request', async () => { + app.router = makeRouter() + onTestFinished(() => { + app.router = undefined + }) + + const router = await runInRequest({ url: '/posts/42?page=2' }, () => + getRouterInstance(), + ) + + expect(router).toBe(app.router) + expect(router.history.location.href).toBe('/posts/42?page=2') + }) + + it('fails in a project without a router entry', async () => { + await expect(runInRequest(() => getRouterInstance())).rejects.toThrow( + 'This project has no router entry', + ) + }) + }) +}) + +describe('concurrent requests', () => { + it('keep their requests, responses and request mocks apart', async () => { + const tag = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { tag: 'real' } }), + ) + const readTag = defineServerFn([tag], ({ context }) => { + setResponseHeader('x-tag', context.tag) + return context.tag + }) + const request = (name: string, delay: number) => + runInRequest({ url: `/${name}` }, async () => { + mockMiddleware(tag, ({ next }) => next({ context: { tag: name } })) + await new Promise((resolve) => setTimeout(resolve, delay)) + const value = await readTag() + return [value, getResponseHeader('x-tag'), getRequest().url] + }) + + const [a, b] = await Promise.all([request('a', 20), request('b', 0)]) + + expect(a).toEqual(['a', 'a', 'http://localhost/a']) + expect(b).toEqual(['b', 'b', 'http://localhost/b']) + }) +}) + +// Through Start's setup file, which runs each test in its own async context. +describe.concurrent('concurrent tests', () => { + const tag = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { tag: 'real' } }), + ) + const readTag = defineServerFn([tag], ({ context }) => context.tag) + const later = (ms: number) => + new Promise((resolve) => setTimeout(resolve, ms)) + + for (const [name, delay] of [ + ['a', 20], + ['b', 0], + ] as const) { + it(`each get their own mock of the same middleware, outside of runInRequest (${name})`, async () => { + mockMiddleware(tag, ({ next }) => next({ context: { tag: name } })) + await later(delay) + + await expect(runInRequest(() => readTag())).resolves.toBe(name) + }) + } +}) + +describe('mockMiddleware', () => { + const realServer = vi.fn() + const realClient = vi.fn() + const auth = createMiddleware({ type: 'function' }) + .client(({ next }) => { + realClient() + return next() + }) + .server(({ next }) => { + realServer() + return next({ context: { user: 'real' } }) + }) + const whoAmI = defineServerFn([auth], ({ context }) => context.user) + + // Registered at the top of the file: stays for every test of the file. + const fileLevel = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { source: 'real' } }), + ) + const readSource = defineServerFn( + [fileLevel], + ({ context }) => context.source, + ) + mockMiddleware(fileLevel, ({ next }) => + next({ context: { source: 'file mock' } }), + ) + + it('replaces the server function of a middleware and switches its client function off', async () => { + realServer.mockClear() + realClient.mockClear() + const mock = vi.fn(({ next }) => next({ context: { user: 'mocked' } })) + mockMiddleware(auth, mock) + + await expect(runInRequest(() => whoAmI({ data: 'x' }))).resolves.toBe( + 'mocked', + ) + + expect(mock).toHaveBeenCalledWith( + expect.objectContaining({ data: 'x', method: 'GET' }), + ) + expect(realServer).not.toHaveBeenCalled() + expect(realClient).not.toHaveBeenCalled() + }) + + it('ends with the test that registered it', async () => { + realServer.mockClear() + realClient.mockClear() + + await expect(runInRequest(() => whoAmI())).resolves.toBe('real') + + expect(realServer).toHaveBeenCalledTimes(1) + expect(realClient).toHaveBeenCalledTimes(1) + }) + + it('stays for the file when it was registered at the top of the file', async () => { + await expect(runInRequest(() => readSource())).resolves.toBe('file mock') + }) + + it('belongs to the request when it is registered inside runInRequest', async () => { + await runInRequest(async () => { + mockMiddleware(fileLevel, ({ next }) => + next({ context: { source: 'request mock' } }), + ) + + await expect(readSource()).resolves.toBe('request mock') + }) + + await expect(runInRequest(() => readSource())).resolves.toBe('file mock') + }) + + it('ends with its request also for work that the request left running', async () => { + let later: Promise | undefined + + await runInRequest(async () => { + mockMiddleware(fileLevel, ({ next }) => + next({ context: { source: 'request mock' } }), + ) + await expect(readSource()).resolves.toBe('request mock') + // (a call that the request schedules and does not wait for) + later = new Promise((resolve) => setTimeout(resolve, 10)).then(() => + readSource(), + ) + }) + + await expect(later).resolves.toBe('file mock') + }) + + it('fails the request when a mock registered inside it never ran', async () => { + await expect( + runInRequest(() => { + mockMiddleware(auth, ({ next }) => next({ context: { user: 'x' } })) + }), + ).rejects.toThrow( + 'A middleware was mocked inside runInRequest() and did not run in that request.', + ) + }) + + it('reports the error of the callback, not a mock that never ran because of it', async () => { + const error = new Error('from the callback') + + await expect( + runInRequest(() => { + mockMiddleware(auth, ({ next }) => next({ context: { user: 'x' } })) + throw error + }), + ).rejects.toBe(error) + }) + + it('lets a mock end the call by throwing', async () => { + const error = new Error('not signed in') + mockMiddleware(auth, () => { + throw error + }) + + await expect(runInRequest(() => whoAmI())).rejects.toBe(error) + }) + + it('replaces a global request middleware when it is registered before the request', async () => { + const real = vi.fn() + const tenantMiddleware = createMiddleware().server(({ next }) => { + real() + return next({ context: { tenant: 'real' } }) + }) + useGlobalMiddleware({ request: [tenantMiddleware] }) + const readTenant = defineServerFn([], ({ context }) => context.tenant) + mockMiddleware(tenantMiddleware, ({ next, request }) => + next({ context: { tenant: new URL(request.url).hostname } }), + ) + + await expect( + runInRequest({ url: 'https://acme.example/' }, () => readTenant()), + ).resolves.toBe('acme.example') + expect(real).not.toHaveBeenCalled() + }) + + it('lets the mock of a request middleware end the request with a response', async () => { + const gate = createMiddleware().server(({ next }) => next()) + useGlobalMiddleware({ request: [gate] }) + mockMiddleware(gate, () => new Response(null, { status: 403 })) + + await expect(runInRequest(() => 'unreached')).rejects.toThrow( + /ended the request with status 403/, + ) + }) + + it('needs a middleware', () => { + expect(() => + mockMiddleware({} as AnyFunctionMiddleware, ({ next }) => next()), + ).toThrow('mockMiddleware() needs a middleware') + }) +}) + +describe('runMiddleware', () => { + it('calls the server function of a function middleware with the input', async () => { + const middleware = createMiddleware({ type: 'function' }) + .validator((input: { id: string }) => input) + .server(({ data, next }) => { + if (getCookie('session') !== 'abc') { + throw new Error('not signed in') + } + return next({ + context: { user: { id: data.id } }, + sendContext: { seen: true }, + }) + }) + + await runInRequest({ headers: { cookie: 'session=abc' } }, async () => { + const next = vi.fn(() => 'the handler result') + const run = await runMiddleware(middleware, { data: { id: '42' } }, next) + + expect(run.context).toEqual({ user: { id: '42' } }) + expect(run.sendContext).toEqual({ seen: true }) + expect(run.result).toBe('the handler result') + expect(next).toHaveBeenCalledWith({ + context: { user: { id: '42' } }, + sendContext: { seen: true }, + }) + }) + + await runInRequest(async () => { + await expect( + runMiddleware(middleware, { data: { id: '42' } }), + ).rejects.toThrow('not signed in') + }) + }) + + it('merges the context of the input with what the middleware adds', async () => { + const parent = createMiddleware({ type: 'function' }).server(({ next }) => + next({ context: { tenant: 'acme' } }), + ) + const middleware = createMiddleware({ type: 'function' }) + .middleware([parent]) + .server(({ next, context }) => + next({ context: { greeting: `hello ${context.tenant}` } }), + ) + + const run = await runInRequest(() => + runMiddleware(middleware, { context: { tenant: 'other' } }), + ) + + // (only this middleware ran: `parent` would have set `acme`) + expect(run.context).toEqual({ tenant: 'other', greeting: 'hello other' }) + expect(run.result).toBeUndefined() + }) + + it('calls the server function of a request middleware for the request of the scope', async () => { + const middleware = createMiddleware().server( + async ({ next, request, pathname, handlerType }) => { + if (!request.headers.get('authorization')) { + return new Response(null, { status: 401 }) + } + const result = await next({ context: { pathname, handlerType } }) + result.response.headers.set('x-checked', 'yes') + return result + }, + ) + + await runInRequest({ url: '/admin' }, async () => { + const next = vi.fn() + const run = await runMiddleware(middleware, {}, next) + + expect(run.response.status).toBe(401) + expect(next).not.toHaveBeenCalled() + }) + + await runInRequest( + { url: '/admin', headers: { authorization: 'Bearer x' } }, + async () => { + const run = await runMiddleware( + middleware, + {}, + () => new Response('page', { status: 203 }), + ) + + expect(run.context).toEqual({ + pathname: '/admin', + handlerType: 'router', + }) + expect(run.response.status).toBe(203) + expect(run.response.headers.get('x-checked')).toBe('yes') + await expect(run.response.text()).resolves.toBe('page') + }, + ) + }) + + it('treats a thrown response of a request middleware as its answer', async () => { + const middleware = createMiddleware().server(() => { + throw new Response(null, { status: 302, headers: { location: '/login' } }) + }) + + const run = await runInRequest(() => runMiddleware(middleware, {})) + + expect(run.response.status).toBe(302) + expect(run.response.headers.get('location')).toBe('/login') + }) + + it('applies what a request middleware set through the response helpers', async () => { + const middleware = createMiddleware().server(({ next }) => { + setResponseHeader('x-frame-options', 'DENY') + return next() + }) + + const run = await runInRequest(() => + runMiddleware(middleware, { handlerType: 'serverFn' }), + ) + + expect(run.response.headers.get('x-frame-options')).toBe('DENY') + }) + + it('runs the real server function of a middleware that is mocked', async () => { + const middleware = createMiddleware({ type: 'function' }).server( + ({ next }) => next({ context: { source: 'real' } }), + ) + mockMiddleware(middleware, ({ next }) => + next({ context: { source: 'mock' } }), + ) + + const run = await runInRequest(() => runMiddleware(middleware, {})) + + expect(run.context).toEqual({ source: 'real' }) + }) + + it('has to be called inside runInRequest', async () => { + const middleware = createMiddleware({ type: 'function' }).server( + ({ next }) => next(), + ) + + await expect(runMiddleware(middleware, {})).rejects.toThrow( + 'runMiddleware() has to be called inside runInRequest()', + ) + }) + + it('needs a middleware with a server function', async () => { + const clientOnly = createMiddleware({ type: 'function' }).client( + ({ next }) => next(), + ) + + await expect( + runInRequest(() => runMiddleware(clientOnly, {})), + ).rejects.toThrow('the middleware has no server function') + }) +}) diff --git a/packages/start-server-core/vite.config.ts b/packages/start-server-core/vite.config.ts index 09e3bf95397..f191fd99bca 100644 --- a/packages/start-server-core/vite.config.ts +++ b/packages/start-server-core/vite.config.ts @@ -44,6 +44,7 @@ export default mergeConfig( './src/request-response.ts', './src/constants.ts', './src/virtual-modules.ts', + './src/testing/index.ts', './src/fake-start-server-fn-resolver.ts', './src/empty-plugin-adapters.ts', ], diff --git a/packages/start-storage-context/src/async-local-storage.ts b/packages/start-storage-context/src/async-local-storage.ts index bbde7046298..b79464149fa 100644 --- a/packages/start-storage-context/src/async-local-storage.ts +++ b/packages/start-storage-context/src/async-local-storage.ts @@ -57,7 +57,11 @@ export function getStartContext(opts?: { const context = startStorage.getStore() if (!context && opts?.throwIfNotFound !== false) { throw new Error( - `No Start context found in AsyncLocalStorage. Make sure you are using the function within the server runtime.`, + `No Start context found in AsyncLocalStorage. Make sure you are using the function within the server runtime.${ + process.env.NODE_ENV === 'test' + ? ` In a test, run this code inside runInRequest(), which the testing/server entry of your Start package exports (for example '@tanstack/react-start/testing/server').` + : '' + }`, ) } return context as any diff --git a/packages/vue-start/package.json b/packages/vue-start/package.json index 1c5020c85e1..313c8879aab 100644 --- a/packages/vue-start/package.json +++ b/packages/vue-start/package.json @@ -50,6 +50,24 @@ "default": "./dist/esm/client-rpc.js" } }, + "./testing": { + "import": { + "types": "./dist/esm/testing.d.ts", + "default": "./dist/esm/testing.js" + } + }, + "./testing/client-rpc": { + "import": { + "types": "./dist/esm/testing/client-rpc.d.ts", + "default": "./dist/esm/testing/client-rpc.js" + } + }, + "./testing/server": { + "import": { + "types": "./dist/esm/testing/server.d.ts", + "default": "./dist/esm/testing/server.js" + } + }, "./server-rpc": { "import": { "types": "./dist/esm/server-rpc.d.ts", diff --git a/packages/vue-start/src/testing.ts b/packages/vue-start/src/testing.ts new file mode 100644 index 00000000000..0384b6fb657 --- /dev/null +++ b/packages/vue-start/src/testing.ts @@ -0,0 +1,10 @@ +export { + mockServerFn, + resetServerFnMocks, +} from '@tanstack/start-client-core/testing' +export type { + AnyClientServerFn, + ServerFnMock, + ServerFnMockContext, + ServerFnMockData, +} from '@tanstack/start-client-core/testing' diff --git a/packages/vue-start/src/testing/client-rpc.ts b/packages/vue-start/src/testing/client-rpc.ts new file mode 100644 index 00000000000..80b041a3885 --- /dev/null +++ b/packages/vue-start/src/testing/client-rpc.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-client-core/testing/client-rpc' diff --git a/packages/vue-start/src/testing/server.ts b/packages/vue-start/src/testing/server.ts new file mode 100644 index 00000000000..ec2ad1c8d87 --- /dev/null +++ b/packages/vue-start/src/testing/server.ts @@ -0,0 +1 @@ +export * from '@tanstack/start-server-core/testing' diff --git a/packages/vue-start/vite.config.ts b/packages/vue-start/vite.config.ts index dc421ef7ffe..17b824ec6d9 100644 --- a/packages/vue-start/vite.config.ts +++ b/packages/vue-start/vite.config.ts @@ -30,6 +30,9 @@ export default mergeConfig( './src/index.ts', './src/client.tsx', './src/client-rpc.ts', + './src/testing.ts', + './src/testing/client-rpc.ts', + './src/testing/server.ts', './src/ssr-rpc.ts', './src/server-rpc.ts', './src/server.tsx', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 945c6cae4de..08dabb1e7e2 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -15064,7 +15064,7 @@ importers: version: 8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0) vite-plugin-solid: specifier: ^2.11.10 || ^3.0.0-0 - version: 2.11.16(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) + version: 2.11.11(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) zod: specifier: 'catalog:' version: 4.5.4 @@ -15612,6 +15612,9 @@ importers: '@tanstack/router-utils': specifier: workspace:* version: link:../router-utils + '@tanstack/start-client-core': + specifier: workspace:* + version: link:../start-client-core '@tanstack/start-server-core': specifier: workspace:* version: link:../start-server-core @@ -29417,16 +29420,6 @@ packages: '@testing-library/jest-dom': optional: true - vite-plugin-solid@2.11.16: - resolution: {integrity: sha512-qguFUmqY2ICuoGHrZjm+cWpvKkqVyWDMptipC/BIEGr9q6wEzwTWYOjM9pEWJ+yoTuF6T5OpysI2Okdy7rsVlQ==} - peerDependencies: - '@testing-library/jest-dom': ^5.16.6 || ^5.17.0 || ^6.0.0 || ^7.0.0 - solid-js: 1.9.12 - vite: ^8.3.8 - peerDependenciesMeta: - '@testing-library/jest-dom': - optional: true - vite-tsconfig-paths@6.1.1: resolution: {integrity: sha512-2cihq7zliibCCZ8P9cKJrQBkfgdvcFkOOc3Y02o3GWUDLgqjWsZudaoiuOwO/gzTzy17cS5F7ZPo4bsnS4DGkg==} peerDependencies: @@ -44770,21 +44763,6 @@ snapshots: transitivePeerDependencies: - supports-color - vite-plugin-solid@2.11.16(@testing-library/jest-dom@6.6.3)(solid-js@1.9.12)(supports-color@10.2.2)(vite@8.3.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): - dependencies: - '@babel/core': 7.29.7(supports-color@10.2.2) - '@types/babel__core': 7.20.5 - babel-preset-solid: 1.9.10(@babel/core@7.29.7(supports-color@10.2.2))(solid-js@1.9.12) - merge-anything: 5.1.7 - solid-js: 1.9.12 - solid-refresh: 0.6.3(solid-js@1.9.12)(supports-color@10.2.2) - vite: 8.3.8(@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.8(@types/node@25.0.9)(esbuild@0.28.1)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)) - optionalDependencies: - '@testing-library/jest-dom': 6.6.3 - transitivePeerDependencies: - - supports-color - vite-tsconfig-paths@6.1.1(@typescript/typescript6@6.0.2)(supports-color@10.2.2)(vite@8.3.8(@types/node@25.0.9)(esbuild@0.27.4)(jiti@2.7.0)(sass-embedded@1.105.1)(sass@1.97.2)(terser@5.51.2)(tsx@4.20.3)(yaml@2.9.0)): dependencies: debug: 4.4.3(supports-color@10.2.2) diff --git a/scripts/e2e/run-as-installed.md b/scripts/e2e/run-as-installed.md index d8de9193645..5d5e78ec649 100644 --- a/scripts/e2e/run-as-installed.md +++ b/scripts/e2e/run-as-installed.md @@ -101,6 +101,14 @@ To look at a copy after a failure: node ../../../scripts/e2e/run-as-installed.mjs --keep vitest run ``` +## Type checks + +`e2e/react-start/vitest-*` also type-check as installed (`test:e2e:types`). +In the workspace pnpm installs `vitest` once per set of peers, so +`@tanstack/start-client-core` and an e2e project can resolve different copies, +and the types that Start adds to Vitest's test context reach only one of them. +A user's project has one copy, and so does the installed copy. + ## In CI `pnpm test:pr` runs `test:e2e` of every affected project, and `test:ci` runs