Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading