From a5e5ac0e88e12a599ab05dce0d28a4b17cf1ce9c Mon Sep 17 00:00:00 2001 From: Alexander Uskov Date: Tue, 18 Apr 2023 17:24:30 +0300 Subject: [PATCH 1/2] spyOn should support zero key in objects (fix #14077) --- .../jest-mock/src/__tests__/index.test.ts | 22 +++++++++++++++++++ packages/jest-mock/src/index.ts | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/packages/jest-mock/src/__tests__/index.test.ts b/packages/jest-mock/src/__tests__/index.test.ts index 8f178c896b8d..3b57ffe83e9e 100644 --- a/packages/jest-mock/src/__tests__/index.test.ts +++ b/packages/jest-mock/src/__tests__/index.test.ts @@ -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, ''); + }).toThrow('No property name supplied'); + expect(() => { + moduleMocker.spyOn({} as Record, NaN); + }).toThrow('No property name supplied'); + expect(() => { + moduleMocker.spyOn({}, undefined); + }).toThrow('No property name supplied'); expect(() => { moduleMocker.spyOn({}, 'method'); }).toThrow( @@ -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 = { diff --git a/packages/jest-mock/src/index.ts b/packages/jest-mock/src/index.ts index 6801429f1626..ccef29b35ae8 100644 --- a/packages/jest-mock/src/index.ts +++ b/packages/jest-mock/src/index.ts @@ -1168,7 +1168,7 @@ export class ModuleMocker { ); } - if (!methodKey) { + if (!methodKey && !Number.isFinite(methodKey)) { throw new Error('No property name supplied'); } From a77fc462932c717cdac24bca2571f359bed87049 Mon Sep 17 00:00:00 2001 From: Alexander Uskov Date: Tue, 18 Apr 2023 17:35:43 +0300 Subject: [PATCH 2/2] fix(jest-mock): spyOn should support `0` key in objects (#14077) --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 309e3d342619..3bf5e28a11da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ - `[jest-mock]` Tweak typings to allow `jest.replaceProperty()` replace methods ([#14008](https://github.com/facebook/jest/pull/14008)) - `[jest-snapshot]` Fix a potential bug when not using prettier and improve performance ([#14036](https://github.com/facebook/jest/pull/14036)) - `[@jest/transform]` Do not instrument `.json` modules ([#14048](https://github.com/facebook/jest/pull/14048)) +- `[jest-mock]` Fix `jest.spyOn()` to correctly handle `0` as a method/property name ([#14082](https://github.com/facebook/jest/pull/14082)) ### Chore & Maintenance