如何使用 Jest 测试返回 void 的函数?打字稿

时间:2021-07-22 22:22:40

标签: typescript ts-jest

我在文件 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} `)
}

我想测试 test 以确保函数 retryNTimes 有效。然后测试以确保它在失败时最多调用 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 | })

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

到目前为止,我一直很不擅长开玩笑,因此非常感谢您对设置这些测试的任何帮助。

1 个答案:

答案 0 :(得分:0)

您想使用模拟功能:

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
        }
    }
}