Skip to content

Commit

Permalink
fix: add multiple globals in VM+JSDOM (fix #4199) (#4202)
Browse files Browse the repository at this point in the history
  • Loading branch information
nstepien authored Oct 1, 2023
1 parent e744d9e commit fc947ce
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
22 changes: 19 additions & 3 deletions packages/vitest/src/integrations/env/jsdom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,25 @@ export default <Environment>({
// TODO: browser doesn't expose Buffer, but a lot of dependencies use it
dom.window.Buffer = Buffer

// inject structuredClone if it exists
if (typeof structuredClone !== 'undefined' && !dom.window.structuredClone)
dom.window.structuredClone = structuredClone
// inject web globals if they missing in JSDOM but otherwise available in Nodejs
// https://nodejs.org/dist/latest/docs/api/globals.html
const globalNames = [
'structuredClone',
'fetch',
'Request',
'Response',
'BroadcastChannel',
'MessageChannel',
'MessagePort',
] as const
for (const name of globalNames) {
const value = globalThis[name]
if (
typeof value !== 'undefined'
&& typeof dom.window[name] === 'undefined'
)
dom.window[name] = value
}

return {
getVmContext() {
Expand Down
21 changes: 21 additions & 0 deletions test/core/test/environments/jsdom.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// @vitest-environment jsdom

import { expect, test } from 'vitest'

const nodeMajor = Number(process.version.slice(1).split('.')[0])

test.runIf(nodeMajor >= 15)('MessageChannel and MessagePort are available', () => {
expect(MessageChannel).toBeDefined()
expect(MessagePort).toBeDefined()
})

test.runIf(nodeMajor >= 17)('structuredClone is available', () => {
expect(structuredClone).toBeDefined()
})

test.runIf(nodeMajor >= 18)('fetch, Request, Response, and BroadcastChannel are available', () => {
expect(fetch).toBeDefined()
expect(Request).toBeDefined()
expect(Response).toBeDefined()
expect(BroadcastChannel).toBeDefined()
})

0 comments on commit fc947ce

Please sign in to comment.