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