嘲弄函数的结果,但不计算调用的次数



我有以下代码:

const results: MessagingDeviceResult[] = [{ messageId: "some unique value"}]
const response = { results } as MessagingDevicesResponse
const returnValue = Promise.resolve<MessagingDevicesResponse>(response)
const spy = jest.spyOn(admin.messaging(), 'sendToDevice').mockReturnValue(returnValue)
pushNotification({
from,
to,
body,
})
expect(spy).toHaveBeenCalledTimes(1)

在控制台上,我可以检查是否调用了mock函数,因为我在代码

上添加了console.log

const { results } = await admin.messaging().sendToDevice(tokens, payload)
console.log('results', results)

,结果:

console.log
results [ { messageId: 'some unique value' } ]

但是,当我调用toHaveBeenCalledTimes(1)来检查函数是否被调用时,Jest告诉我没有被调用!

expect(jest.fn()).toHaveBeenCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0

导致这种情况的常见情况是什么?函数被成功模拟,但没有记录调用次数。

我弄清楚了,pushNotification是async函数,我忘记了awaiton call

await pushNotification({
from,
to,
body,
})

最新更新