簡體   English   中英

開玩笑模擬 function 的結果但不計算調用次數

[英]Jest mock the result of function but not calculating the number of calls

我有以下代碼:

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)

在控制台上,我可以檢查是否調用了模擬的 function,因為我在代碼上添加了一個console.log


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

console.log('results', results)

結果:

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

但是,當我調用toHaveBeenCalledTimes(1)檢查是否調用了 function 時,Jest 告訴我沒有調用!

expect(jest.fn()).toHaveBeenCalledTimes(expected)

Expected number of calls: 1
Received number of calls: 0

可能導致這種情況的常見情況是什么? function被mock成功但沒有注冊調用次數。

我想通了,pushNotification 是async的 function 我忘記了await呼叫

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM