Skip to content

Commit

Permalink
spyOn should support zero key in objects (fix jestjs#14077)
Browse files Browse the repository at this point in the history
  • Loading branch information
octaharon committed Apr 18, 2023
1 parent 15af9b3 commit a5e5ac0
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
22 changes: 22 additions & 0 deletions packages/jest-mock/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1308,6 +1308,15 @@ describe('moduleMocker', () => {
expect(() => {
moduleMocker.spyOn(null, 'method');
}).toThrow('spyOn could not find an object to spy on for method');
expect(() => {
moduleMocker.spyOn({} as Record<string, any>, '');
}).toThrow('No property name supplied');
expect(() => {
moduleMocker.spyOn({} as Record<number, any>, NaN);
}).toThrow('No property name supplied');
expect(() => {
moduleMocker.spyOn({}, undefined);
}).toThrow('No property name supplied');
expect(() => {
moduleMocker.spyOn({}, 'method');
}).toThrow(
Expand All @@ -1320,6 +1329,19 @@ describe('moduleMocker', () => {
);
});

it('should not throw when spying on a method named `0`', () => {
let haveBeenCalled = false;
const obj = {
0: () => {
haveBeenCalled = true;
},
};
const spy = moduleMocker.spyOn(obj, 0);
obj[0].call(null);
expect(haveBeenCalled).toBe(true);
expect(spy).toHaveBeenCalled();
});

it('supports clearing a spy', () => {
let methodOneCalls = 0;
const obj = {
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-mock/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1168,7 +1168,7 @@ export class ModuleMocker {
);
}

if (!methodKey) {
if (!methodKey && !Number.isFinite(methodKey)) {
throw new Error('No property name supplied');
}

Expand Down

0 comments on commit a5e5ac0

Please sign in to comment.