typescript 使用Jest测试异步重试

ej83mcc0  于 2023-01-27  发布在  TypeScript
关注(0)|答案(1)|浏览(134)

我有一个函数,我试图用async.retry重试。

export const publish = async (message: string): Promise<void> => {
 sendMessage({ MessageBody: message }, (err, _) => {
    if (err) {
      console.error(`Error: ${err})
      throw Error(`Error`)
    } else {
      console.log(`Published: ${message})
    }
  })
}
async.retry(
3, 
async () => await publish("message"), 
(err, result) => { if (err){ Console.log("Error") } } 
)

我想模拟并测试这个函数是否会使用async.retry重试并返回error/void。

test('retry publish. Returns Error',async () => {
    const publishEventsSpy = jest
    .fn()
    .mockRejectedValueOnce(new Error('Error'))
    .mockRejectedValueOnce(new Error('Error'))

    jest.doMock('../emitEvent', () => {
      return {
        publish: publishSpy,
      }
    })

    async.retry(2,
      publishSpy,
      function(err,result){
        if(err){
          console.log(`Error - ${err}`)
        }
      })

    expect(publishEventsSpy).toHaveBeenCalledTimes(2)
})

我收到此错误:

Expected number of calls: 2
    Received number of calls: 1

我想我是正确的嘲笑这一点,如果我改变期望

expect(publishEventsSpy()).rejects.toThrowError('Error')

一切都过去了。任何帮助都是值得的。

k10s72fa

k10s72fa1#

你可以这样做:

test('retry publish. Returns Error',async () => {
      const publishEventsSpy = jest
        .fn()
        .mockRejectedValueOnce(new Error('Error'))
        .mockRejectedValueOnce(new Error('Error'))

      jest.doMock('../emitEvent', () => {
        return {
          publish: publishEventsSpy,
        }
      })
      
      // ...
      
      await expect(publishEventsSpy()).rejects.toEqual(new Error('Async error'));
      await expect(publishEventsSpy()).rejects.toEqual(new Error('Async error'));
      expect(publishEventsSpy).toHaveBeenCalledTimes(2)
    })

相关问题