如何用 Jest 测试 return 无效的函数?打字稿

How to test a function that return void with Jest? Tyepscript

我在文件中有一些函数和类型 retry.ts

export const retryNTimes =  (retryFunction: Function) => {
    let retry = 0;
    while(retry < MAX_NUMBER_OF_RETRIES){
        try {
            retryFunction()
            break
        } catch (err) {
            console.log(`Try ${retry}: ${err}`)
            retry += 1
        }
    }
} 

type User = {
  userId: string
}

const TestUser = async ({
  userId,
}:User) => {
  console.log(`userid : ${userId} `)
}

我想测试测试以确保函数 retryNTimes works.Then 测试以确保它在失败时最多调用函数 3 次。所以我创建了一个小的 TestUser 函数来执行此操作。

在文件 retry.test.ts

describe('retry Function',() => {

test('retryNTimes function was call', () => {
    retryNTimes(function(){ TestUser()})
    expect(retryNTimes).toHaveBeenCalledTimes(1)
})

test('retry function to try 1 time', () => {
    retryNTimes(function(){ TestUser()})
    expect(TestUser).toHaveBeenCalledTimes(1)
})

 test('retry function to try 2 times', () => {
     retryNTimes(function(){ TestUser()})
     expect(TestUser).toHaveBeenCalledTimes(2)
 })

 test('retry function to try 3 times', () => {
     retryNTimes(function(){ TestUser()})
     expect(TestUser).toHaveBeenCalledTimes(3)
 })

})

但是我在前 2 次测试中收到此错误。

Matcher error: received value must be a mock or spy function

    Received has type:  function
    Received has value: [Function anonymous]

       9 | test('retryNTimes function was call', () => {
      10 |     retryNTimes(function(){ TestUser()})
    > 11 |     expect(retryNTimes).toHaveBeenCalledTimes(1)
         |                         ^
      12 | })

而且我知道后两个不适用于此设置,因为我很确定我需要模拟函数以在再次调用之前捕获错误。

到目前为止,我的玩笑表现很差,因此非常感谢您提供有关设置这些测试的任何帮助。

您想使用模拟函数:

describe('retry Function',() => {

  test('retry function to try 1 time', async () => {
    // create a mock function that rejects once, then resolves
    const func = jest.fn()
            .mockRejectedValueOnce(new Error('intentional test error)')
            .mockResolvedValueOnce(void 0);
    await retryNTimes(func)
    expect(func).toHaveBeenCalledTimes(2)
  })
})

请注意,您还有一些其他问题,主要是您的重试函数不处理异步函数。您需要等待处理:

export const retryNTimes =  async (retryFunction: Function) => {
    let retry = 0;
    while(retry < MAX_NUMBER_OF_RETRIES){
        try {
            await retryFunction()
            break
        } catch (err) {
            console.log(`Try ${retry}: ${err}`)
            retry += 1
        }
    }
}