Skip to content

Commit fc947ce

Browse files
authored
fix: add multiple globals in VM+JSDOM (fix #4199) (#4202)
1 parent e744d9e commit fc947ce

File tree

2 files changed

+40
-3
lines changed

2 files changed

+40
-3
lines changed

packages/vitest/src/integrations/env/jsdom.ts

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,25 @@ export default <Environment>({
6969
// TODO: browser doesn't expose Buffer, but a lot of dependencies use it
7070
dom.window.Buffer = Buffer
7171

72-
// inject structuredClone if it exists
73-
if (typeof structuredClone !== 'undefined' && !dom.window.structuredClone)
74-
dom.window.structuredClone = structuredClone
72+
// inject web globals if they missing in JSDOM but otherwise available in Nodejs
73+
// https://nodejs.org/dist/latest/docs/api/globals.html
74+
const globalNames = [
75+
'structuredClone',
76+
'fetch',
77+
'Request',
78+
'Response',
79+
'BroadcastChannel',
80+
'MessageChannel',
81+
'MessagePort',
82+
] as const
83+
for (const name of globalNames) {
84+
const value = globalThis[name]
85+
if (
86+
typeof value !== 'undefined'
87+
&& typeof dom.window[name] === 'undefined'
88+
)
89+
dom.window[name] = value
90+
}
7591

7692
return {
7793
getVmContext() {
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// @vitest-environment jsdom
2+
3+
import { expect, test } from 'vitest'
4+
5+
const nodeMajor = Number(process.version.slice(1).split('.')[0])
6+
7+
test.runIf(nodeMajor >= 15)('MessageChannel and MessagePort are available', () => {
8+
expect(MessageChannel).toBeDefined()
9+
expect(MessagePort).toBeDefined()
10+
})
11+
12+
test.runIf(nodeMajor >= 17)('structuredClone is available', () => {
13+
expect(structuredClone).toBeDefined()
14+
})
15+
16+
test.runIf(nodeMajor >= 18)('fetch, Request, Response, and BroadcastChannel are available', () => {
17+
expect(fetch).toBeDefined()
18+
expect(Request).toBeDefined()
19+
expect(Response).toBeDefined()
20+
expect(BroadcastChannel).toBeDefined()
21+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy