【问题标题】:Jest mock on function typescript函数打字稿上的笑话
【发布时间】:2019-09-13 14:52:31
【问题描述】:

当我在 Typescript 中编写测试时,这里真的很痛苦。我在 api 中有我的功能

api.ts

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

当我尝试用 Jest 模拟它时。我收到错误消息:类型上不存在属性 mockRejectedValueOnce ...

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

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

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

我尝试将它转换为 any,但我得到了错误

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

尝试了很多方法,但我仍然无法用 Jest 模拟该功能。你们能告诉我正确的方法吗?

谢谢

【问题讨论】:

标签: reactjs jestjs


【解决方案1】:

您只需要使用jest.Mock 类型进行转换。

let mockGetRequest = getRequest as jest.Mock<any>

因为 Typescript 不知道你在调用 jest.mock 后嘲笑了 getModel

【讨论】:

  • 然后当我使用 mockedGetModel.mockRejectedValueOnce("hello")。我收到另一个错误:TS2345:'"hello"' 类型的参数不可分配给'never' 类型的参数。
  • 更新你的答案然后我会接受它let mockGetRequest = getRequest as jest.Mock&lt;any&gt;
猜你喜欢
  • 1970-01-01
  • 2020-07-28
  • 2020-09-09
  • 2020-08-08
  • 2020-11-27
  • 2018-06-21
  • 2018-12-15
  • 1970-01-01
  • 2019-09-26
相关资源
最近更新 更多