Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(spy): update to set initial implementation through normal logic (fixes #3260) #3263

Merged
merged 2 commits into from Apr 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion packages/spy/src/index.ts
Expand Up @@ -324,5 +324,9 @@ export function fn<TArgs extends any[] = any[], R = any>(
export function fn<TArgs extends any[] = any[], R = any>(
implementation?: (...args: TArgs) => R,
): Mock<TArgs, R> {
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
}
13 changes: 12 additions & 1 deletion test/core/test/jest-mock.test.ts
Expand Up @@ -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'
Expand All @@ -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')

Expand Down