coinhndp
coinhndp

Reputation: 2481

Jest mock on function typescript

It is really painful here when I write test in Typescript. I have my function in api

api.ts

export getModel = () => {...} //return a promise

And when I try to mock it with Jest. I got the error: property mockRejectedValueOnce does not exist on type ...

import {getModel as mockGetModel} from './api'

jest.mock('./api, () => {
    return {getModel: jest.fn(() => Promise.resolve())}
})

it('should ...', () => {
  mockGetModel.mockRejectedValueOnce('hello') //error here
}) 

I try to cast it, either as any, and I get the error

TS2349: Cannot invoke an expression whose type lacks a call signature.

Try many ways but I still cannot mock the function with Jest. Could you guys show me the correct way to do it.

Thanks

Upvotes: 1

Views: 1717

Answers (1)

Rannie Aguilar Peralta
Rannie Aguilar Peralta

Reputation: 1752

You just need to cast it with jest.Mock type.

let mockGetRequest = getRequest as jest.Mock<any>

because Typescript doesn't know that you mocked the getModel after calling the jest.mock

Upvotes: 2

Related Questions