From c759a9aacfc5f46c508f6c44a604ef0d01bf50af Mon Sep 17 00:00:00 2001 From: Alex Miller Date: Fri, 28 Apr 2023 00:29:55 +1200 Subject: [PATCH] fix(spy): update to set initial implementation through normal logic (fixes #3260) (#3263) --- packages/spy/src/index.ts | 6 +++++- test/core/test/jest-mock.test.ts | 13 ++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) 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 } 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')