【问题标题】:mockImplementation function signature [closed]mockImplementation 函数签名
【发布时间】:2021-05-02 08:16:28
【问题描述】:

我正在尝试模拟 Firebase 库的 sendToDevice 的结果,但我坚持使用 MessagingDevicesResponse 的返回值(请参阅下面的代码)

import MessagingDevicesResponse = admin.messaging.MessagingDevicesResponse;

const fnMock = (registrationToken, payload) => Promise.resolve<MessagingDevicesResponse>(/* HERE */)

jest.spyOn(admin.messaging(), 'sendToDevice').mockImplementation(fnMock)

如果我简单地传递这样的东西

Promise.resolve<MessagingDevicesResponse>({ canonicalRegistrationTokenCount: 0 })

我得到了错误:

Argument of type '{ canonicalRegistrationTokenCount: number; }' is not assignable to parameter of type 'MessagingDevicesResponse | PromiseLike<MessagingDevicesResponse>'.
  Type '{ canonicalRegistrationTokenCount: number; }' is missing the following properties from type 'MessagingDevicesResponse': failureCount, multicastId, results, successCountts(2345)

如果我尝试:

Promise.resolve<MessagingDevicesResponse>(new MessagingDevicesResponse())

我明白了:

'MessagingDevicesResponse' only refers to a type, but is being used as a value here.ts(2693)

【问题讨论】:

  • Promise.resolve() 确实是Promise&lt;void&gt;,它不解析为任何值。您需要使用MessagingDevicesResponse 解决,否则使用该承诺的代码将无法工作。
  • 编译器再次准确地告诉您问题所在 - { canonicalRegistrationTokenCount: 0 } 不是有效的 MessagingDevicesResponse
  • 推测它是一个类型或接口,而不是一个实际的类,但你实际上并没有显示定义。
  • 那么不清楚你为什么期望new MessagingDevicesResponse() 工作。 JavaScript 没有类型,TypeScript 类型在编译时被删除。
  • 您可以提供一个确实拥有所有相关道具的对象。

标签: typescript firebase jestjs


【解决方案1】:

解决了

const results: MessagingDeviceResult[] = []
const response = { results } as MessagingDevicesResponse
const returnValue = Promise.resolve<MessagingDevicesResponse>(response)
const spy = jest.spyOn(admin.messaging(), 'sendToDevice').mockReturnValue(returnValue)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多