Skip to content

Commit 155837f

Browse files
committed
docs(vitest): how to import modules from global setup file
1 parent 6e43bd5 commit 155837f

File tree

1 file changed

+46
-1
lines changed

1 file changed

+46
-1
lines changed

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

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,49 @@ 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+
While Vitest is instructed to resolve packages for the `workerd` runtime, it runs your global setup file in the NodeJS environment. This is why you might encounter issue importing pacakges like [Postgres.js](https://github.com/cloudflare/workers-sdk/issues/6465) that export non-node version for `workerd`. To get around this issue, you can create a wrapper that uses Vite's SSR module loader to import your global setup file under the correct conditions. Then, adjust your Vitest configuration to point to this wrapper. For example:
68+
69+
```ts
70+
// File: global-setup-wrapper.ts
71+
import { createServer } from "vite"
72+
73+
// Import the actual global setup file with the correct setup
74+
const mod = await viteImport("./global-setup.ts")
75+
76+
export default mod.default;
77+
78+
// Helper to import the file with default node setup
79+
async function viteImport(file: string) {
80+
const server = await createServer({
81+
root: import.meta.dirname,
82+
configFile: false,
83+
server: { middlewareMode: true, hmr: false, watch: null, ws: false },
84+
optimizeDeps: { noDiscovery: true },
85+
clearScreen: false,
86+
});
87+
const mod = await server.ssrLoadModule(file);
88+
await server.close();
89+
return mod;
90+
}
91+
```
92+
93+
```ts
94+
// File: vitest.config.ts
95+
import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config";
96+
97+
export default defineWorkersConfig({
98+
test: {
99+
// Replace the globalSetup with the wrapper file
100+
globalSetup: ["./global-setup-wrapper.ts"],
101+
poolOptions: {
102+
workers: {
103+
// ...
104+
},
105+
},
106+
},
107+
});
108+
```

0 commit comments

Comments
 (0)