When testing a module that has a dependency in a different file. When assigning that module to be jest.Mock
typescript gives an error that the method mock
as jest.Mock
and nothing elseThe most concise way of mocking a module exported as default
in ts-jest that I can think of really boils down to casting the module as jest.Mock
.
Code:
import myDep from '../dependency' // No `* as` here
jest.mock('../dependency')
it('does what I need', () => {
// Only diff with pure JavaScript is the presence of `as jest.Mock`
(myDep as jest.Mock).mockReturnValueOnce('return')
// Call function that calls the mocked module here
// Notice there's no reference to `.default` below
expect(myDep).toHaveBeenCalled()
})
Benefits:
default
property anywhere in the test code - you reference the actual exported function name instead,* as
in the import statement,typeof
keyword,mocked
.