Skip to content

Commit f41763d

Browse files
committed
update docs with example
1 parent b681bb9 commit f41763d

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

src/content/docs/workers/testing/vitest-integration/isolation-and-concurrency.mdx

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,5 +63,49 @@ The Workers Vitest pool works by running code inside a Cloudflare Worker that Vi
6363

6464
Using Vitest Pool Workers may cause your Worker to behave differently when deployed than during testing as the `nodejs_compat` flag is enabled by default. This means that Node.js-specific APIs and modules are available when running your tests. However, Cloudflare Workers do not support these Node.js APIs in the production environment unless you specify this flag in your Worker configuration.
6565

66+
If you do not have a `nodejs_compat` or `nodejs_compat_v2` flag in your configuration and you import a Node.js module in your Worker code, your tests may pass, but you will find that you will not be able to deploy this Worker as the upload call (either via the REST API or via Wrangler) will throw an error.
67+
68+
However, if you use Node.js globals that are not supported by the runtime, your Worker upload will be successful, but you may see errors in production code. Let's create a contrived example to illustrate the issue.
69+
70+
The `wrangler.toml` does not specify either `nodejs_compat` or `nodejs_compat_v2`:
71+
72+
```toml
73+
name = "test"
74+
main = "src/index.ts"
75+
compatibility_date = "2024-12-16"
76+
# no nodejs_compat flags here
77+
```
78+
79+
In our `src/index.ts` file, we use the `process` object, which is a Node.js global, unavailable in the Workerd runtime:
80+
81+
```typescript
82+
export default {
83+
async fetch(request, env, ctx): Promise<Response> {
84+
process.env.TEST = 'test';
85+
return new Response(process.env.TEST);
86+
},
87+
} satisfies ExportedHandler<Env>;
88+
```
89+
90+
The test simple assertion that the Worker managed to use `process`.
91+
92+
```typescript
93+
it('responds with "test"', async () => {
94+
const response = await SELF.fetch('https://example.com/');
95+
expect(await response.text()).toMatchInlineSnapshot(`"test"`);
96+
});
97+
```
98+
99+
Now, if we run `npm run test`, we see that the tests will _pass_:
100+
101+
```
102+
✓ test/index.spec.ts (1)
103+
✓ responds with "test"
104+
105+
Test Files 1 passed (1)
106+
Tests 1 passed (1)
107+
```
108+
109+
And we can run `wrangler dev` and `wrangler deploy` without issues. It _looks like_ our code is fine. However, this code will fail in production as `process` is not available in the Workerd runtime.
66110

67111
:::

0 commit comments

Comments
 (0)