首页 > 解决方案 > 模拟实现函数签名

问题描述

我正在尝试模拟sendToDeviceFirebase 库的结果,但我被返回值困住了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)

标签: typescriptfirebasejestjs

解决方案


解决了

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

推荐阅读