Skip to content

Commit 2912b6e

Browse files
[Vitest Integration] explains how to import modules on the global setup file (#19937)
Co-authored-by: ToriLindsay <[email protected]>
1 parent b7509e6 commit 2912b6e

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

src/content/docs/workers/testing/vitest-integration/known-issues.mdx

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,50 @@ export default defineWorkersConfig({
6060
});
6161
```
6262

63-
You can find an example in the [Recipes](/workers/testing/vitest-integration/recipes) page.
63+
You can find an example in the [Recipes](/workers/testing/vitest-integration/recipes) page.
64+
65+
### Importing modules from global setup file
66+
67+
Although Vitest is set up to resolve packages for the `workerd` runtime, it runs your global setup file in the Node.js environment. This can cause issues when importing packages like [Postgres.js](https://github.com/cloudflare/workers-sdk/issues/6465), which exports a non-Node version for `workerd`.
68+
To work around this, you can create a wrapper that uses Vite's SSR module loader to import the global setup file under the correct conditions. Then, adjust your Vitest configuration to point to this wrapper. For example:
69+
70+
```ts
71+
// File: global-setup-wrapper.ts
72+
import { createServer } from "vite"
73+
74+
// Import the actual global setup file with the correct setup
75+
const mod = await viteImport("./global-setup.ts")
76+
77+
export default mod.default;
78+
79+
// Helper to import the file with default node setup
80+
async function viteImport(file: string) {
81+
const server = await createServer({
82+
root: import.meta.dirname,
83+
configFile: false,
84+
server: { middlewareMode: true, hmr: false, watch: null, ws: false },
85+
optimizeDeps: { noDiscovery: true },
86+
clearScreen: false,
87+
});
88+
const mod = await server.ssrLoadModule(file);
89+
await server.close();
90+
return mod;
91+
}
92+
```
93+
94+
```ts
95+
// File: vitest.config.ts
96+
import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config";
97+
98+
export default defineWorkersConfig({
99+
test: {
100+
// Replace the globalSetup with the wrapper file
101+
globalSetup: ["./global-setup-wrapper.ts"],
102+
poolOptions: {
103+
workers: {
104+
// ...
105+
},
106+
},
107+
},
108+
});
109+
```

0 commit comments

Comments
 (0)