typescript - 模拟实现函数签名
问题描述
我正在尝试模拟sendToDevice
Firebase 库的结果,但我被返回值困住了MessagingDevicesResponse
(请参阅下面的代码中的 HERE)
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)
解决方案
解决了
const results: MessagingDeviceResult[] = []
const response = { results } as MessagingDevicesResponse
const returnValue = Promise.resolve<MessagingDevicesResponse>(response)
const spy = jest.spyOn(admin.messaging(), 'sendToDevice').mockReturnValue(returnValue)
推荐阅读
- javascript - 似乎无法使用括号符号访问某些数据?
- javascript - 格式化字符串变量更漂亮
- java - 无法读取 org.jacoco:jacoco-maven-plugin:jar:0.7.9 的工件描述符
- javascript - 仅当另一个史诗未运行时,我如何才能仅使 redux-observable 史诗继续
- spring-boot - 同一个spring-boot项目的不同设置文件
- python - 使用 python 在 SQL Server 中插入 DATETIME 值
- node.js - 如何使用 nodeJS/Express/Mongo 下载多部分表单数据 rest API
- django - 如何在 ModelSerializer 更新中“忽略数据并保持实例原样”
- makefile - 交叉编译多层makefile
- java - 外部函数签名中是否需要 @PathVariable 或 @RequestBody?