如何使用Jest测试返回void的函数?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正常工作。然后进行测试,确保它在函数失败时最多调用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)
})
})

然而,我在前两次测试中收到了这个错误。

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

最新更新