Skip to content

Commit f6902af

Browse files
morinokamiclaude
andcommitted
fix(vitest): run app tests without starting the Worker
`vp test` stopped with a startup error before running any test in Void apps on the default Cloudflare target, including a fresh `npm create void` app: ReferenceError: module is not defined With `nodejs_compat`, which Void turns on for auth, PostgreSQL, MySQL, Sandbox, and TanStack Start, React Router and vinext apps: Error: AssertionError: depsOptimizer is required in dev mode Vitest loads `vite.config.ts` and starts a Vite server of its own, so the Cloudflare Vite plugin that `voidPlugin()` includes started the Worker there too. Vitest turns off dependency prebundling in nearly every environment, the Worker's included, and the Cloudflare plugin relies on it: a CommonJS dependency such as React reached workerd unconverted, and the plugin's own nodejs_compat polyfill import asserted on the missing optimizer. Users could not remove the plugin, and `test.deps.optimizer` does not bring discovery back. ## Fix `isVitestServer()` recognizes the server that Vitest creates by the plugins Vitest adds to it (`vitest`, `vitest:*`), in any `--mode`. A server that a test starts through Vite's API, and `vp dev --mode test`, are not Vitest's and keep everything. In Vitest's server: - The plugins of Void's Cloudflare wrapper, the Cloudflare Vite plugin included, do not apply, in Void apps and in framework apps. Void's other plugins still resolve `void/*`, `@schema` and the generated modules, so tests can import route handlers and page loaders. - `migrationPlugin` does not apply, so a test run no longer migrates the local D1 database or the PostgreSQL or MySQL database in `.env`. - The AI project setup prints its hint instead of prompting. Tests run in Node.js, so a call that reaches a binding still throws `env: Cloudflare env is unavailable`; `vi.mock()` can replace the binding module. ## Tests - Unit: the detection, the Cloudflare wrapper and the migration plugin with and without Vitest's plugins (modes `test` and `staging`), and the AI setup prompt. - Integration: `vp test` in isolated copies of the React Pages playground (as is, with `nodejs_compat` and with `--mode staging`) and the TanStack Start playground. - Packed consumer: Vite+ fixtures run `vp test` with a mocked binding. ## Docs Add a Testing guide: `vp test` needs no configuration, tests run in Node.js without bindings, and test files stay out of the convention directories. Link it from the email testing sections and the Void skill, and note the Vitest server in the package AGENTS.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7848d23 commit f6902af

17 files changed

Lines changed: 442 additions & 11 deletions

‎.github/scripts/packed-consumer.mjs‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,22 @@ try {
341341
[join(fixture, 'node_modules/typescript/bin/tsc'), '--noEmit'],
342342
fixture,
343343
);
344+
if (useVitePlus) {
345+
// Vitest loads the app's Vite config, Void's plugin included, and runs the tests in
346+
// Node.js. The test from docs/guide/testing.md replaces the KV module it uses.
347+
mkdirSync(join(fixture, 'src'), { recursive: true });
348+
writeFileSync(
349+
join(fixture, 'src/visits.ts'),
350+
`import { kv } from 'void/kv';\nexport async function countVisit(): Promise<number> {\n const visits = ((await kv.get<number>('visits')) ?? 0) + 1;\n await kv.put('visits', visits);\n return visits;\n}\n`,
351+
);
352+
writeFileSync(
353+
join(fixture, 'src/visits.test.ts'),
354+
`import { expect, it, vi } from 'vite-plus/test';\nimport { loader } from '../pages/index.server';\nimport { countVisit } from './visits';\nvi.mock('void/kv', () => {\n const values = new Map<string, unknown>();\n return { kv: { get: async (key: string) => values.get(key) ?? null, put: async (key: string, value: unknown) => { values.set(key, value); } } };\n});\nit('counts visits', async () => {\n await countVisit();\n expect(await countVisit()).toBe(2);\n});\nit('imports a page loader', () => {\n expect(loader).toBeTypeOf('function');\n});\n`,
355+
);
356+
await run(process.execPath, [vite, 'test', 'run'], fixture);
357+
rmSync(join(fixture, 'src/visits.ts'));
358+
rmSync(join(fixture, 'src/visits.test.ts'));
359+
}
344360
// The installed package must find and verify every bundled runtime artifact.
345361
await run(
346362
process.execPath,
@@ -496,7 +512,7 @@ if (runtime.manifest.platformVersion !== ${JSON.stringify(version)}) throw new E
496512
}
497513
}
498514
console.log(
499-
`Passed packed ${label} (${suite}): init, frozen install, ${useVitePlus ? 'Vite+' : 'public Vite'} build/typecheck, assets, KV, email, runtime integrity${full ? ', dev/preview, hydration/navigation' : ', dev HTTP'}${framework === 'react' ? ', Node target' : ''}`,
515+
`Passed packed ${label} (${suite}): init, frozen install, ${useVitePlus ? 'Vite+ build/typecheck/test' : 'public Vite build/typecheck'}, assets, KV, email, runtime integrity${full ? ', dev/preview, hydration/navigation' : ', dev HTTP'}${framework === 'react' ? ', Node target' : ''}`,
500516
);
501517
} catch (error) {
502518
failures.push({ fixture: label, error: String(error.stack ?? error) });

‎TESTING.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,8 @@ node --test --test-timeout=10000 .github/scripts/packed-*.test.mjs
245245

246246
`VOID_PACKED_PM=npm|pnpm` and `VOID_PACKED_FRAMEWORK=react|vue|svelte|solid` select a focused
247247
local run. `VOID_PACKED_TOOLCHAIN=vite-plus` verifies Vite+ initialization, the workspace's
248-
tested Vite+ version, and the generated `vp` build/dev/preview commands. CI checks a React
248+
tested Vite+ version, the generated `vp` build/dev/preview commands, and `vp test` with the
249+
app's Vite config. CI checks a React
249250
app with Vite+ for both package managers alongside the plain Vite coverage.
250251
The interactive initializer is a Node.js script using the system `script` PTY
251252
utility and Bash; it has no Python or native npm dependency.

‎docs/.vitepress/config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,7 @@ export default extendConfig(
317317
icon: 'lucide:rocket',
318318
collapsed: false,
319319
items: [
320+
{ text: 'Testing', link: '/guide/testing' },
320321
{ text: 'Remote Development', link: '/guide/remote-dev' },
321322
{ text: 'Deploying Your App', link: '/guide/deployment' },
322323
{ text: 'Project Collaboration', link: '/guide/project-collaboration' },

‎docs/guide/email/receiving.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,4 +138,4 @@ describe('email handlers', () => {
138138
});
139139
```
140140

141-
The harness matches handlers in the same order as deployed email routes.
141+
The harness matches handlers in the same order as deployed email routes. [Testing](../testing.md) explains how to run tests and how to test code that uses other bindings.

‎docs/guide/email/sending.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,6 @@ describe('signup flow', () => {
254254
});
255255
```
256256

257-
The harness intercepts every `sendEmail` call until `dispose()` is called. `clear()` empties the captured list without releasing the sink.
257+
The harness intercepts every `sendEmail` call until `dispose()` is called. `clear()` empties the captured list without releasing the sink. [Testing](../testing.md) explains how to run tests and how to test code that uses other bindings.
258258

259259
To handle incoming messages, see [Receiving Email](./receiving.md).

‎docs/guide/testing.md‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
outline: deep
3+
---
4+
5+
# Testing
6+
7+
Test your app with [Vitest](https://vitest.dev/). With Vite+, the default toolchain, run it with `vp test`:
8+
9+
```sh
10+
vp test
11+
```
12+
13+
Import test APIs from `vite-plus/test`. With the Vite toolchain, add `vitest` to your dev dependencies, run `vitest`, and import from `vitest` instead.
14+
15+
Vitest reads your `vite.config.ts`, so `void/*` imports, `@schema`, and the other modules Void provides resolve in tests as they do in your app. Tests need no separate configuration.
16+
17+
Keep test files out of the [convention directories](../reference/structure.md) such as `routes/` and `pages/`. Void reads the files there as part of your app, so a test file in `routes/` becomes a route. Put tests in `tests/`, or next to the code they test in `src/`.
18+
19+
## Bindings {#bindings}
20+
21+
Tests run in Node.js, not in the Workers runtime. Void doesn't start your Worker for a test run, so D1, KV, R2, and other bindings are unavailable, and it doesn't apply migrations to your local database. You can import modules that use bindings, but a call that reaches one throws `env: Cloudflare env is unavailable`.
22+
23+
To test code that uses a binding, replace its module with [`vi.mock()`](https://vitest.dev/api/vi#vi-mock):
24+
25+
```ts
26+
// src/visits.ts
27+
import { kv } from 'void/kv';
28+
29+
export async function countVisit(): Promise<number> {
30+
const visits = ((await kv.get<number>('visits')) ?? 0) + 1;
31+
await kv.put('visits', visits);
32+
return visits;
33+
}
34+
```
35+
36+
```ts
37+
// src/visits.test.ts
38+
import { expect, it, vi } from 'vite-plus/test';
39+
import { countVisit } from './visits';
40+
41+
vi.mock('void/kv', () => {
42+
const values = new Map<string, unknown>();
43+
return {
44+
kv: {
45+
get: async (key: string) => values.get(key) ?? null,
46+
put: async (key: string, value: unknown) => {
47+
values.set(key, value);
48+
},
49+
},
50+
};
51+
});
52+
53+
it('counts visits', async () => {
54+
await countVisit();
55+
expect(await countVisit()).toBe(2);
56+
});
57+
```
58+
59+
## Email {#email}
60+
61+
`void/email/testing` captures sent and received email in tests. See [Testing](./email/sending.md#testing) in Sending Email and [Testing inbound handlers](./email/receiving.md#testing-inbound-handlers) in Receiving Email.

‎packages/void/AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ production functions and real generated entries rather than copied code.
222222

223223
- **Workers types 5 still declares the Buffer constructor as `any`.** In the mixed Node/Workers type environment, this also affects `node:buffer`'s exported value. CLI code and tests that need Buffer constructor inference or narrowing use `cli/node-buffer.ts`, which retains Node's `BufferConstructor` signatures. Keep `workers-node-globals.typecheck.ts` covering constructor checks and Node Buffer instance methods.
224224
- **Cloudflare browser login needs all terminal streams.** `cf auth login` prints its device confirmation code to stderr, so the auth and deploy runners inherit stdin, stdout, and stderr only for login; credential reads stay captured. Keep the asynchronous platform runner cancellable.
225+
- **Vitest runs an app's tests in a Vite server of its own.** That server loads the app's Vite config, so serve plugins run there too, but Vitest turns off dependency prebundling, which the Cloudflare plugin needs to start the Worker (`module is not defined`, or `depsOptimizer is required in dev mode` with `nodejs_compat`). `isVitestServer()` in `plugin-dev-config.ts` recognizes the server by Vitest's plugin names, in any `--mode`. `cloudflare()` and `migrationPlugin` do not apply there, and the AI setup prints its hint instead of prompting. A server that a test starts through Vite's API keeps them all. Gate new dev-server work that changes a database or asks questions the same way; code generation still runs. `test/integration/vitest-app.test.ts` runs the tests of a Void app and a framework app; check Vitest's plugin names again when updating it.
225226
- **Cloudflare compatibility flags must be merged as a set.** The Cloudflare plugin concatenates callback arrays with the resolved generated config. `mergeBindings` must emit the union once and clear the in-memory fallback, preserving all distinct flags without rewriting authored config. Existing Worker handoff copies production flags into the generated Cloudflare config, so concatenation otherwise causes upload error `10021` (`Compatibility flag specified multiple times`). Keep real-build coverage for `cloudflare` and `worker` overlap.
226227
- **`__VOID_ISR_DEPLOYMENT_ID` must be a compile-time literal.** `router/compile.ts` stringifies `crypto.randomUUID()` once at build time (`export const __VOID_ISR_DEPLOYMENT_ID = "..."`, exactly like `__VOID_BUILD_KEY`) so every isolate of a deployment shares one id. A bare runtime `crypto.randomUUID()` per-isolate in the emitted source would mint a fresh id per isolate, so the edge-cache key (`handleIsr`'s `deploymentId` option) and the KV key (`env.__VOID_ISR_DEPLOYMENT_ID`, also used by the `revalidate()` purge path) would disagree — breaking cache reads and on-demand purge.
227228
- **Self-host ISR requires a user-declared `ISR_CACHE` KV.** There is no `id: 'local'` injection for it: a placeholder id is fine for miniflare-backed dev but breaks a real `wrangler deploy`, which rejects an unknown namespace id. The user creates the namespace and binds it as `ISR_CACHE`; `readIsrCache`/`writeIsrCache` fail open to a live render when it is absent.

‎packages/void/skills/void/SKILL.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ Use `void deploy --skip-migrations` when database migrations run separately; it
5656
| SSR and caching | `docs/guide/ssr.md`, `docs/guide/edge/*.md` |
5757
| HTTPS, rewrites, redirects, fallbacks | `docs/guide/edge/rewrites.md`, `docs/guide/edge/redirects.md`, `docs/reference/config.md` |
5858
| Static site generation | `docs/guide/ssg.md` |
59+
| Testing an app with Vitest (`vp test`) | `docs/guide/testing.md` |
5960
| Connected apps and artifact preparation | `docs/guide/platform/administration/connected-apps.md`, `docs/reference/api/deploy.md` |
6061
| Deployment and CI | `docs/guide/deployment.md`, `docs/reference/cli/deploy.md` |
6162
| Install or maintain a company platform | `docs/guide/self-hosted-platform.md`, `docs/reference/cli/platform-installation.md` |

‎packages/void/src/index.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import {
4343
isViteBuildOrPreview,
4444
getOrCreateDevTriggerToken,
4545
devTriggerSecretGuardPlugin,
46+
isVitestServer,
4647
selectVoidCloudflareLogin,
4748
} from './plugin-dev-config.ts';
4849
import { devTriggersHintPlugin } from './plugin-dev-triggers-hint.ts';
@@ -542,7 +543,9 @@ export function voidPlugin(options?: {
542543
);
543544
});
544545
} else if (credentials.status === 'no-project') {
545-
if (process.stdin.isTTY) {
546+
// A test run must not stop for questions, and Vitest's watch mode reads keys from
547+
// the terminal, so Vitest's server gets the hint below.
548+
if (process.stdin.isTTY && !isVitestServer(server.config)) {
546549
// Fire-and-forget interactive setup
547550
afterServerReady(server, () => {
548551
console.log();

‎packages/void/src/plugin-cloudflare.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
type WorkerConfig,
1919
} from './plugin-cloudflare-config.ts';
2020
import { withLocalPreviewBindings } from './plugin-cloudflare-preview.ts';
21+
import { isVitestServer } from './plugin-dev-config.ts';
2122
import { writeFileAtomic } from './shared/atomic-write.ts';
2223
import { CLOUDFLARE_DEPLOY_BUILD_ENV } from './shared/env.ts';
2324

@@ -28,6 +29,24 @@ function isInside(directory: string, path: string): boolean {
2829
return child !== '..' && !child.startsWith('../') && !isAbsolute(child);
2930
}
3031

32+
/**
33+
* Vitest runs tests in Node.js, in a Vite server of its own that turns off dependency
34+
* prebundling. The Cloudflare plugin needs prebundling to start the Worker, so the Worker would
35+
* fail before any test runs. Leave these plugins out of that server; Void's other plugins still
36+
* resolve `void/*`, `@schema` and the generated modules for tests.
37+
*/
38+
function skipOnVitestServer(plugins: Array<Plugin>): Array<Plugin> {
39+
for (const plugin of plugins) {
40+
const apply = plugin.apply;
41+
plugin.apply = (config, environment) =>
42+
!isVitestServer(config) &&
43+
(typeof apply === 'function'
44+
? apply(config, environment)
45+
: apply === undefined || apply === environment.command);
46+
}
47+
return plugins;
48+
}
49+
3150
/** Keep Void's public configuration and artifact layout while running the v2 plugin. */
3251
export function cloudflare(options: {
3352
configPath?: string;
@@ -218,7 +237,7 @@ export function cloudflare(options: {
218237
},
219238
},
220239
};
221-
return [
240+
return skipOnVitestServer([
222241
bridge,
223242
directories,
224243
...withLocalPreviewBindings(
@@ -237,5 +256,5 @@ export function cloudflare(options: {
237256
root,
238257
),
239258
output,
240-
];
259+
]);
241260
}

0 commit comments

Comments
 (0)