From 294ccf68341b3ebf4cdcde26b0c7e71f1b95ef38 Mon Sep 17 00:00:00 2001 From: Vladimir Sheremet Date: Tue, 2 Aug 2022 11:45:39 +0300 Subject: [PATCH 1/2] fix: correctly restore globals in env teardown --- packages/vitest/src/integrations/env/utils.ts | 3 ++- test/core/test/env-runtime.test.ts | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 test/core/test/env-runtime.test.ts diff --git a/packages/vitest/src/integrations/env/utils.ts b/packages/vitest/src/integrations/env/utils.ts index 07e2ff14ecd2..bada94c967c9 100644 --- a/packages/vitest/src/integrations/env/utils.ts +++ b/packages/vitest/src/integrations/env/utils.ts @@ -4,6 +4,7 @@ const allowRewrite = [ 'Event', 'EventTarget', 'MessageEvent', + // implemented in Node 18 'ArrayBuffer', ] @@ -41,7 +42,7 @@ export function populateGlobal(global: any, win: any, options: PopulateOptions = const keys = getWindowKeys(global, win) const originals = new Map( - allowRewrite.map(([key]) => [key, global[key]]), + allowRewrite.filter(key => key in global).map(key => [key, global[key]]), ) const overrideObject = new Map() diff --git a/test/core/test/env-runtime.test.ts b/test/core/test/env-runtime.test.ts new file mode 100644 index 000000000000..add7a1d85d17 --- /dev/null +++ b/test/core/test/env-runtime.test.ts @@ -0,0 +1,14 @@ +import { populateGlobal } from 'vitest/src/integrations/env/utils' +import { expect, test, vi } from 'vitest' + +test('returns valid globals', () => { + const globalEvent = vi.fn() + const winEvent = vi.fn() + const global = { + Event: globalEvent, + } + const win = { Event: winEvent } + const { originals } = populateGlobal(global, win) + expect(originals.get('Event')).toBe(globalEvent) + expect(win.Event).toBe(winEvent) +}) From f548b805d4e8d4938d37fb696d817e1a73fdc70a Mon Sep 17 00:00:00 2001 From: Vladimir Sheremet Date: Tue, 2 Aug 2022 11:46:44 +0300 Subject: [PATCH 2/2] test: more tests --- test/core/test/env-runtime.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/test/core/test/env-runtime.test.ts b/test/core/test/env-runtime.test.ts index add7a1d85d17..44de8b9afb1c 100644 --- a/test/core/test/env-runtime.test.ts +++ b/test/core/test/env-runtime.test.ts @@ -11,4 +11,5 @@ test('returns valid globals', () => { const { originals } = populateGlobal(global, win) expect(originals.get('Event')).toBe(globalEvent) expect(win.Event).toBe(winEvent) + expect(global.Event).toBe(winEvent) })