From 60a5dff18cb5430b94608cec326aeeb94ae7f3ca Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Thu, 27 Apr 2023 11:24:35 +1200 Subject: [PATCH 1/2] test: add failing test cases for initial implementation not being exposed --- test/core/test/jest-mock.test.ts | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/test/core/test/jest-mock.test.ts b/test/core/test/jest-mock.test.ts index 92ef87786881..12bb6fa189ae 100644 --- a/test/core/test/jest-mock.test.ts +++ b/test/core/test/jest-mock.test.ts @@ -41,6 +41,17 @@ describe('jest mock compat layer', () => { expect(Spy.mock.instances).toHaveLength(0) }) + it('implementation is set correctly on init', () => { + const impl = () => 1 + const mock1 = vi.fn(impl) + + expect(mock1.getMockImplementation()).toEqual(impl) + + const mock2 = vi.fn() + + expect(mock2.getMockImplementation()).toBeUndefined() + }) + it('implementation sync fn', () => { const originalFn = function () { return 'original' @@ -49,7 +60,7 @@ describe('jest mock compat layer', () => { spy() // returns 'original' - expect(spy.getMockImplementation()).toBe(undefined) + expect(spy.getMockImplementation()).toBe(originalFn) spy.mockReturnValueOnce('2-once').mockReturnValueOnce('3-once') From 7055b2387aadcb7ee6206af3c91fa4b17095280f Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Thu, 27 Apr 2023 11:28:59 +1200 Subject: [PATCH 2/2] fix: set implementation if one is provided This allows the internals to properly store the implementation, allowing it to be acquired via `getMockImplementation`. --- packages/spy/src/index.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/spy/src/index.ts b/packages/spy/src/index.ts index 812459518a75..02c9a7e60362 100644 --- a/packages/spy/src/index.ts +++ b/packages/spy/src/index.ts @@ -324,5 +324,9 @@ export function fn( export function fn( implementation?: (...args: TArgs) => R, ): Mock { - return enhanceSpy(tinyspy.internalSpyOn({ fn: implementation || (() => {}) }, 'fn')) as unknown as Mock + const enhancedSpy = enhanceSpy(tinyspy.internalSpyOn({ spy: () => {} }, 'spy')) + if (implementation) + enhancedSpy.mockImplementation(implementation) + + return enhancedSpy as Mock }