Skip to content

Commit

Permalink
fix: don't bind global classes (#1345)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va committed May 21, 2022
1 parent b802d5e commit 195cc58
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
18 changes: 15 additions & 3 deletions packages/vitest/src/integrations/env/utils.ts
Expand Up @@ -26,6 +26,10 @@ export function getWindowKeys(global: any, win: any) {
return keys
}

function isClassLikeName(name: string) {
return name[0] === name[0].toUpperCase()
}

interface PopulateOptions {
bindFunctions?: boolean
}
Expand All @@ -40,13 +44,21 @@ export function populateGlobal(global: any, win: any, options: PopulateOptions =

const overrideObject = new Map<string | symbol, any>()
for (const key of keys) {
const bindedFunction = bindFunctions && typeof win[key] === 'function' && win[key].bind(win)
// we bind functions such as addEventListener and others
// because they rely on `this` in happy-dom, and in jsdom it
// has a priority for getting implementaion from symbols
// (global doesn't have these symbols, but window - does)
const boundFunction = bindFunctions
&& typeof win[key] === 'function'
&& !isClassLikeName(key)
&& win[key].bind(win)

Object.defineProperty(global, key, {
get() {
if (overrideObject.has(key))
return overrideObject.get(key)
if (bindedFunction)
return bindedFunction
if (boundFunction)
return boundFunction
return win[key]
},
set(v) {
Expand Down
6 changes: 6 additions & 0 deletions test/core/test/dom.test.ts
Expand Up @@ -126,3 +126,9 @@ it('globals are the same', () => {
expect(window.globalThis.Blob).toBe(globalThis.Blob)
expect(Blob).toBe(globalThis.Blob)
})

it('can extend global class', () => {
class SuperBlob extends Blob {}

expect(SuperBlob).toBeDefined()
})

0 comments on commit 195cc58

Please sign in to comment.