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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/start-test-single-module.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@tanstack/start-plugin-core': patch
'@tanstack/start-server-core': patch
---

`mockMiddleware` can now replace a middleware that is created in the file of a server function that uses it. In a Vitest run, a file with server functions is one module on the server. Before, the server loaded the file a second time for the handlers of its functions, as it does in the app, and the mock did not reach the middleware object of that second module.
4 changes: 1 addition & 3 deletions docs/start/framework/react/guide/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -425,8 +425,6 @@ A mock registered inside the callback of `runInRequest` belongs to that request.

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.
Expand Down Expand Up @@ -562,5 +560,5 @@ The request middleware of `src/start.ts` has already run when the callback of `r
- 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.
- A file with server functions is one module in a server test. In the app, the server loads such a file a second time for the handlers of its functions, so there a handler and the other code of the file each have their own copy of the file's module state. A test does not show a mistake that depends on this.
- The route tree is not regenerated while Vitest watches.
15 changes: 12 additions & 3 deletions e2e/react-start/vitest-app/src/posts.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { notFound } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import { createMiddleware, createServerFn } from '@tanstack/react-start'
import { setResponseHeader } from '@tanstack/react-start/server'
import { authMiddleware } from './middleware/auth'
import { addLike, countPosts, findPost } from './server-only'
import { addLike, countDrafts, countPosts, findPost } from './server-only'

export const fetchPost = createServerFn()
.validator((postId: string) => postId)
Expand All @@ -14,7 +14,16 @@ export const fetchPost = createServerFn()
return post
})

export const fetchPostCount = createServerFn().handler(() => countPosts())
// A middleware that is created in the file of the server function that uses
// it. A test replaces it with `mockMiddleware` like one in a file of its own
// (see tests/posts.server.test.ts).
export const draftsMiddleware = createMiddleware({ type: 'function' }).server(
({ next }) => next({ context: { drafts: countDrafts() } }),
)

export const fetchPostCount = createServerFn()
.middleware([draftsMiddleware])
.handler(({ context }) => countPosts() + context.drafts)

export const likePost = createServerFn({ method: 'POST' })
.middleware([authMiddleware])
Expand Down
5 changes: 5 additions & 0 deletions e2e/react-start/vitest-app/src/server-only.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,18 @@ const posts = new Map<string, Record<Locale, string>>([
['3', { en: 'The third post', de: 'Der dritte Beitrag' }],
])
const users = new Map<string, User>([['ada', { id: 'u1', name: 'Ada' }]])
const drafts = new Set<string>()
const likes = new Map<string, Set<string>>()
const calls: Array<string> = []

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

export function countDrafts(): number {
return drafts.size
}

export function findPost(id: string, locale: Locale): Post | undefined {
const titles = posts.get(id)
return titles && { id, title: titles[locale] }
Expand Down
18 changes: 17 additions & 1 deletion e2e/react-start/vitest-app/tests/posts.server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,12 @@ import {
} from '@tanstack/react-start/testing/server'
import { expect, test } from 'vitest'
import { authMiddleware } from '../src/middleware/auth'
import { fetchPost, likePost } from '../src/posts'
import {
draftsMiddleware,
fetchPost,
fetchPostCount,
likePost,
} from '../src/posts'
import { recordedCalls } from '../src/server-only'

test('runInRequest resolves to what a server function returns', async () => {
Expand Down Expand Up @@ -50,6 +55,17 @@ test('the middleware of a server function refuses a request without a session',
)
})

// `draftsMiddleware` is created in src/posts.ts, the file of `fetchPostCount`.
test('mockMiddleware replaces a middleware that is created in the file of its server function', async () => {
await expect(runInRequest(() => fetchPostCount())).resolves.toBe(3)

mockMiddleware(draftsMiddleware, ({ next }) =>
next({ context: { drafts: 2 } }),
)

await expect(runInRequest(() => fetchPostCount())).resolves.toBe(5)
})

test('mockMiddleware puts a user of the test in place of the session', async () => {
mockMiddleware(authMiddleware, ({ next }) =>
next({ context: { user: { id: 'u2', name: 'Grace' } } }),
Expand Down
4 changes: 2 additions & 2 deletions e2e/react-start/vitest-library/src/session.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
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).
// The middleware of `account.ts`. A test replaces 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
Expand Down
12 changes: 5 additions & 7 deletions e2e/react-start/vitest-library/tests/greeting.server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,15 @@ test('mockServerFn refuses a server function in a server 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 () => {
// `secretMiddleware` is created in the file of `greet`.
test('mockMiddleware replaces a middleware that is created in the file of its server function', async () => {
await expect(
runInRequest(async () => {
runInRequest(() => {
mockMiddleware(secretMiddleware, ({ next }) =>
next({ context: { secret: 'a mocked secret' } }),
)

await greet({ data: 'Ada' })
return greet({ data: 'Ada' })
}),
).rejects.toThrow('Create the middleware in a file of its own to mock it.')
).resolves.toBe('Hello Ada, a mocked secret')
})
7 changes: 7 additions & 0 deletions packages/start-plugin-core/src/start-compiler/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -590,6 +590,12 @@ export class StartCompiler {
compilerTransforms?: Array<StartCompilerImportTransform> | undefined
compilerPlugins?: Array<StartCompilerPlugin> | undefined
serverFnProviderModuleDirectives?: ReadonlyArray<string> | undefined
/**
* Compile a server module that declares server functions as the caller
* and the provider at once, instead of a caller next to a provider
* module. The file is then evaluated once. A test run sets this.
*/
singleServerFnModule?: boolean
warn?: (message: string) => void
/**
* Returns the currently known server functions from previous builds.
Expand Down Expand Up @@ -1427,6 +1433,7 @@ export class StartCompiler {
getKnownServerFns: this.options.getKnownServerFns,
serverFnProviderModuleDirectives:
this.options.serverFnProviderModuleDirectives,
singleServerFnModule: this.options.singleServerFnModule ?? false,
onServerFnsById: this.options.onServerFnsById,
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,12 @@ function generateCallerRpcStub(
* - Creates an extractedFn that calls __executeServer
* - Modifies .handler() to pass (extractedFn, serverFn) - two arguments
*
* For a server module of a test run (`singleServerFnModule`):
* - Rewrites the server function like a provider file does, in the module
* that declares it, and leaves the exports of the module alone
* - A call from server code then runs the handler of the same module, and the
* file is evaluated once
*
* @param candidates - All ServerFn candidates to process
* @param context - The compilation context with helpers and mutable state
* @returns Result containing runtime code to add, or null if no candidates processed
Expand All @@ -204,6 +210,12 @@ export function handleCreateServerFn(
)
}

// A caller that keeps its handlers. Only a request to the URL of a server
// function still resolves to the provider file.
const isSingleModule =
context.singleServerFnModule && context.env === 'server' && !isProviderFile
const keepsHandlers = isProviderFile || isSingleModule

// Get environment-specific configuration
const envConfig = getEnvConfig(context, isProviderFile)

Expand Down Expand Up @@ -325,7 +337,7 @@ export function handleCreateServerFn(
}
}

if (isProviderFile) {
if (keepsHandlers) {
// PROVIDER FILE: This is the extracted file that contains the actual implementation
// We need to:
// 1. Create an extractedFn that calls __executeServer
Expand Down Expand Up @@ -447,7 +459,7 @@ export function handleCreateServerFn(
// Add runtime import using cached AST node
const runtimeCode = getCachedRuntimeCode(
context.framework,
envConfig.runtimeCodeType,
keepsHandlers ? 'provider' : envConfig.runtimeCodeType,
)
context.ast.program.body.unshift(t.cloneNode(runtimeCode))
}
Expand Down
2 changes: 2 additions & 0 deletions packages/start-plugin-core/src/start-compiler/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export interface CreateStartCompilerOptions {
compilerTransforms?: Array<StartCompilerImportTransform> | undefined
compilerPlugins?: Array<StartCompilerPlugin> | undefined
serverFnProviderModuleDirectives?: ReadonlyArray<string> | undefined
singleServerFnModule?: boolean
warn?: (message: string) => void
onServerFnsById?: (d: Record<string, ServerFn>) => void
getKnownServerFns: () => Record<string, ServerFn>
Expand Down Expand Up @@ -55,6 +56,7 @@ export function createStartCompiler(
compilerTransforms: options.compilerTransforms,
compilerPlugins: options.compilerPlugins,
serverFnProviderModuleDirectives: options.serverFnProviderModuleDirectives,
singleServerFnModule: options.singleServerFnModule,
warn: options.warn,
getKnownServerFns: options.getKnownServerFns,
devServerFnModuleSpecifierEncoder: options.encodeModuleSpecifierInDev,
Expand Down
5 changes: 5 additions & 0 deletions packages/start-plugin-core/src/start-compiler/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ export interface CompilationContext extends StartCompilerTransformContext {
getKnownServerFns: () => Record<string, ServerFn>
/** Module-level directives to add to extracted server function provider files. */
serverFnProviderModuleDirectives: ReadonlyArray<string> | undefined
/**
* Whether a server module that declares server functions is the caller and
* the provider at once. A test run sets this.
*/
singleServerFnModule: boolean

/**
* Callback when server functions are discovered.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,8 @@ export interface StartCompilerPluginOptions {
*/
providerEnvName: string
/**
* Whether the bundler runs for a test runner. The resolver of a test run
* Whether the bundler runs for a test runner. A test run compiles a server
* module that declares server functions as one module, and its resolver
* finds a server function without the compiler's record of it.
*/
isTestRun?: () => boolean
Expand Down Expand Up @@ -469,6 +470,7 @@ export function startCompilerPlugin(
compilerTransforms,
compilerPlugins,
serverFnProviderModuleDirectives,
singleServerFnModule: opts.isTestRun?.(),
onServerFnsById,
getKnownServerFns: () => serverFnsById,
encodeModuleSpecifierInDev:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { describe, expect, test } from 'vitest'
import {
compileCode,
compileFor,
evaluateModule,
importSources,
} from '../regression-helpers'

// A test run compiles a server module that declares server functions as the
// caller and the provider at once (`singleServerFnModule`), so that the file
// is evaluated once and its handlers share its state with its other code.

const head = `import { createServerFn } from '@tanstack/react-start'\n`
const single = { singleServerFnModule: true }

async function compileSingle(code: string, options = {}) {
const compiled = await compileFor('ssr', code, { ...single, ...options })
expect(compiled.code).not.toBeNull()
return { code: compiled.code!, serverFns: compiled.serverFns }
}

describe('a server module of a test run', () => {
test('runs a handler in the module that declares it', async () => {
const { code } = await compileSingle(`${head}let count = 0
export const increment = createServerFn().handler(() => ++count)
export function read() {
return count
}`)
const module = await evaluateModule(code)

expect(await module.increment()).toBe(1)
expect(module.read()).toBe(1)
})

test('keeps the exports of the module and adds none', async () => {
const { code } =
await compileSingle(`${head}const local = createServerFn().handler(() => 'local')
export const exported = createServerFn().handler(() => 'exported')
export const callLocal = () => local()
export default 1`)
const module = await evaluateModule(code)

expect(Object.keys(module).sort()).toEqual([
'callLocal',
'default',
'exported',
])
expect(await module.exported()).toBe('exported')
expect(await module.callLocal()).toBe('local')
})

test('keeps what only a handler imports', async () => {
const { code } =
await compileSingle(`${head}import { db } from './db.server'
export const fn = createServerFn().handler(() => db.x())`)

expect(importSources(code)).toEqual(['./db.server'])
const module = await evaluateModule(code, {
'./db.server': `export const db = { x: () => 'x' }`,
})
expect(await module.fn()).toBe('x')
})

test('reports its server functions under the ids of the other outputs', async () => {
const code = `${head}export const fn = createServerFn().handler(() => 1)`
const caller = await compileFor('ssr', code)
const { serverFns } = await compileSingle(code)

expect(Object.keys(serverFns)).toHaveLength(1)
expect(serverFns).toEqual(caller.serverFns)
})

test('gets no directive of the provider module', async () => {
const { code } = await compileSingle(
`${head}export const fn = createServerFn().handler(() => 1)`,
{ directives: ['use server-entry'] },
)

expect(code).not.toContain('use server-entry')
})
})

describe('the other outputs of a test run', () => {
const code = `${head}import { db } from './db.server'
export const fn = createServerFn().handler(() => db.x())`

test('the client module calls over RPC', async () => {
expect(await compileCode('client', code, single)).toBe(
await compileCode('client', code),
)
})

// A request to the URL of a server function resolves to this module.
test('the provider module is still there', async () => {
expect(await compileCode('provider', code, single)).toBe(
await compileCode('provider', code),
)
})
})
3 changes: 3 additions & 0 deletions packages/start-plugin-core/tests/regression-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ interface StartCompilerOptions {
/** `serverFnProviderModuleDirectives` */
directives?: Array<string>
compilerPlugins?: Array<StartCompilerPlugin>
/** `singleServerFnModule`: how a test run compiles server modules. */
singleServerFnModule?: boolean
}

/**
Expand All @@ -51,6 +53,7 @@ export function createStartCompiler(options: StartCompilerOptions) {
devServerFnModuleSpecifierEncoder: ({ extractedFilename, root }) =>
`/@id${extractedFilename.slice(root.length)}`,
serverFnProviderModuleDirectives: options.directives,
singleServerFnModule: options.singleServerFnModule,
onServerFnsById: (fns) => Object.assign(serverFns, fns),
loadModule: async (id) => {
const code = files[id]
Expand Down
6 changes: 2 additions & 4 deletions packages/start-server-core/src/testing/middlewareMocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,8 @@ export function mockMiddleware<TMiddleware extends AnyMiddleware>(
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.',
'A middleware was mocked inside runInRequest() and did not run in that request. 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().',
),
})
}
Expand Down
Loading