From 195cc5857a5ed04455fb3df1d452400b0f07554e Mon Sep 17 00:00:00 2001 From: Vladimir Date: Sat, 21 May 2022 09:01:16 +0300 Subject: [PATCH] fix: don't bind global classes (#1345) --- packages/vitest/src/integrations/env/utils.ts | 18 +++++++++++++++--- test/core/test/dom.test.ts | 6 ++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/packages/vitest/src/integrations/env/utils.ts b/packages/vitest/src/integrations/env/utils.ts index 7906247a4fcf..074cd9bb5adf 100644 --- a/packages/vitest/src/integrations/env/utils.ts +++ b/packages/vitest/src/integrations/env/utils.ts @@ -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 } @@ -40,13 +44,21 @@ export function populateGlobal(global: any, win: any, options: PopulateOptions = const overrideObject = new Map() 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) { diff --git a/test/core/test/dom.test.ts b/test/core/test/dom.test.ts index ae1bd7105e15..1be843461d7a 100644 --- a/test/core/test/dom.test.ts +++ b/test/core/test/dom.test.ts @@ -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() +})