DEV Community

Discussion on: Testing with Jest and TypeScript, the tricky parts

Collapse
 
wolfhoundjesse profile image
Jesse M. Holmes

I ran into something in this category with mocking a module with jest.mock().

import { fetchResource } from 'utils/api'

jest.mock('utils/api')
Enter fullscreen mode Exit fullscreen mode

This alone is enough to mock fetchResource, but with TypeScript we still get the intellisense from the original function rather than the mock function. I just reassigned fetchResource and typed the new function:

import { fetchResource } from 'utils/api'

jest.mock('utils/api')
const mockFetch = fetchResource as jest.Mock
Enter fullscreen mode Exit fullscreen mode

Finally I had access to things like fetchResource.mockResolvedValueOnce()

Collapse
 
learosema profile image
Lea Rosema (she/her)

Cool, learned something new today, thank you =)

Collapse
 
pscoriae profile image
Pierre Cesario

You just ended my hour long search for a solution. Many thanks!