Skip to content

Commit 62e120b

Browse files
authored
fix: make sure mocks as global variable for multiple versions of muk-prop (#4)
<!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Introduced a global mechanism for managing mock items, improving accessibility across module systems. - Added a new function to retrieve and manage mock items globally. - **Bug Fixes** - Enhanced the mock restoration process for better efficiency and reliability. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 1e2b166 commit 62e120b

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

src/index.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,15 @@ export interface MockItem {
66
hasOwnProperty: boolean;
77
}
88

9-
let mocks: MockItem[] = [];
9+
const MOCKS = Symbol.for('@cnpmjs/muk-prop mocks');
10+
// make sure mocks is a global variable for multiple versions of muk-prop
11+
// in the same process, e.g.: CommonJS and ES module
12+
function getMocks() {
13+
if (!Reflect.has(globalThis, MOCKS)) {
14+
Reflect.set(globalThis, MOCKS, []);
15+
}
16+
return Reflect.get(globalThis, MOCKS) as MockItem[];
17+
}
1018

1119
const cache = new Map<any, Set<any>>();
1220

@@ -15,7 +23,7 @@ const cache = new Map<any, Set<any>>();
1523
*/
1624
export function mock(obj: any, key: PropertyKey, value?: any) {
1725
const hasOwnProperty = Object.hasOwn(obj, key);
18-
mocks.push({
26+
getMocks().push({
1927
obj,
2028
key,
2129
descriptor: Object.getOwnPropertyDescriptor(obj, key)!,
@@ -61,8 +69,9 @@ export const muk = mock;
6169
* Restore all mocks
6270
*/
6371
export function restore() {
64-
for (let i = mocks.length - 1; i >= 0; i--) {
65-
const m = mocks[i];
72+
const mocks = getMocks();
73+
while (mocks.length) {
74+
const m = mocks.pop()!;
6675
if (!m.hasOwnProperty) {
6776
// Delete the mock key, use key on the prototype
6877
delete m.obj[m.key];
@@ -71,7 +80,6 @@ export function restore() {
7180
Object.defineProperty(m.obj, m.key, m.descriptor);
7281
}
7382
}
74-
mocks = [];
7583
cache.clear();
7684
}
7785

0 commit comments

Comments
 (0)