Skip to content

Commit c759a9a

Browse files
authoredApr 27, 2023
fix(spy): update to set initial implementation through normal logic (fixes #3260) (#3263)
1 parent 481b1fd commit c759a9a

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed
 

‎packages/spy/src/index.ts

+5-1
Original file line numberDiff line numberDiff line change
@@ -324,5 +324,9 @@ export function fn<TArgs extends any[] = any[], R = any>(
324324
export function fn<TArgs extends any[] = any[], R = any>(
325325
implementation?: (...args: TArgs) => R,
326326
): Mock<TArgs, R> {
327-
return enhanceSpy(tinyspy.internalSpyOn({ fn: implementation || (() => {}) }, 'fn')) as unknown as Mock
327+
const enhancedSpy = enhanceSpy(tinyspy.internalSpyOn({ spy: () => {} }, 'spy'))
328+
if (implementation)
329+
enhancedSpy.mockImplementation(implementation)
330+
331+
return enhancedSpy as Mock
328332
}

‎test/core/test/jest-mock.test.ts

+12-1
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ describe('jest mock compat layer', () => {
4141
expect(Spy.mock.instances).toHaveLength(0)
4242
})
4343

44+
it('implementation is set correctly on init', () => {
45+
const impl = () => 1
46+
const mock1 = vi.fn(impl)
47+
48+
expect(mock1.getMockImplementation()).toEqual(impl)
49+
50+
const mock2 = vi.fn()
51+
52+
expect(mock2.getMockImplementation()).toBeUndefined()
53+
})
54+
4455
it('implementation sync fn', () => {
4556
const originalFn = function () {
4657
return 'original'
@@ -49,7 +60,7 @@ describe('jest mock compat layer', () => {
4960

5061
spy() // returns 'original'
5162

52-
expect(spy.getMockImplementation()).toBe(undefined)
63+
expect(spy.getMockImplementation()).toBe(originalFn)
5364

5465
spy.mockReturnValueOnce('2-once').mockReturnValueOnce('3-once')
5566

0 commit comments

Comments
 (0)
Please sign in to comment.