From 684bdd2d4518ecf8a94122e4c37edaa01d3d4ef8 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Sun, 22 Dec 2024 11:48:49 +0800 Subject: [PATCH] fix: make sure mocks is a global variable for multiple versions of muk-prop --- src/index.ts | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/src/index.ts b/src/index.ts index f1af2b6..edfb6e2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -6,7 +6,15 @@ export interface MockItem { hasOwnProperty: boolean; } -let mocks: MockItem[] = []; +const MOCKS = Symbol.for('@cnpmjs/muk-prop mocks'); +// make sure mocks is a global variable for multiple versions of muk-prop +// in the same process, e.g.: CommonJS and ES module +function getMocks() { + if (!Reflect.has(globalThis, MOCKS)) { + Reflect.set(globalThis, MOCKS, []); + } + return Reflect.get(globalThis, MOCKS) as MockItem[]; +} const cache = new Map>(); @@ -15,7 +23,7 @@ const cache = new Map>(); */ export function mock(obj: any, key: PropertyKey, value?: any) { const hasOwnProperty = Object.hasOwn(obj, key); - mocks.push({ + getMocks().push({ obj, key, descriptor: Object.getOwnPropertyDescriptor(obj, key)!, @@ -61,8 +69,9 @@ export const muk = mock; * Restore all mocks */ export function restore() { - for (let i = mocks.length - 1; i >= 0; i--) { - const m = mocks[i]; + const mocks = getMocks(); + while (mocks.length) { + const m = mocks.pop()!; if (!m.hasOwnProperty) { // Delete the mock key, use key on the prototype delete m.obj[m.key]; @@ -71,7 +80,6 @@ export function restore() { Object.defineProperty(m.obj, m.key, m.descriptor); } } - mocks = []; cache.clear(); }