Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: make sure mocks as global variable for multiple versions of muk-prop #4

Merged
merged 1 commit into from
Dec 22, 2024
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