Skip to content

Commit fc947ce

Browse files
authoredOct 1, 2023
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
 

Diff for: ‎packages/vitest/src/integrations/env/jsdom.ts

+19-3
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() {

Diff for: ‎test/core/test/environments/jsdom.spec.ts

+21
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)
Please sign in to comment.