Skip to content

Commit

Permalink
fix: make sure mocks is a global variable for multiple versions of mu…
Browse files Browse the repository at this point in the history
…k-prop
  • Loading branch information
fengmk2 committed Dec 22, 2024
1 parent 1e2b166 commit 684bdd2
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<any, Set<any>>();

Expand All @@ -15,7 +23,7 @@ const cache = new Map<any, Set<any>>();
*/
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)!,
Expand Down Expand Up @@ -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];
Expand All @@ -71,7 +80,6 @@ export function restore() {
Object.defineProperty(m.obj, m.key, m.descriptor);
}
}
mocks = [];
cache.clear();
}

Expand Down

0 comments on commit 684bdd2

Please sign in to comment.