我在使用 jest toThrowError
函数时遇到问题。
我有一个函数,使用redis来设置调用函数的限制,即每次调用这个函数时使用一个键,它调用redis.incr(key)
,如果number 超过指定的限制,该函数将抛出 LIMITED
错误,否则该函数将不返回任何内容。
为了简单起见,让我们像这样定义这个函数:
async function fn(key) {
const count = await redis.incr(key)
if(count > limit)
throw new Error('LIMITED')
// do other stuff.
}
现在我想测试 fn
的这个功能,所以如果 limit=2
我调用 fn
两次,如果我再次调用它必须抛出 LIMITED
错误。
这是我的测试:
it('should throw LIMITED error', async () => {
const key = 'somekey'
await fn(key)
await fn(key)
expect(async () => { await fn(key) }).toThrowError('LIMITED')
}
但是当我运行测试时,它说:
Expected the function to throw an error matching:
"LIMITED"
But it didn't throw anything.
这很奇怪,因为当我将测试代码更改为如下内容时:
it('should throw LIMITED error', async () => {
const key = 'somekey'
await fn(key)
await fn(key)
await fn(key)
}
然后它在运行测试期间抛出 LIMITED
错误并失败。
我不确定我是否理解在尝试测试函数行为时 jest expect 函数究竟是如何工作的,所以如果有任何更好的方法来完成这种测试,我将不胜感激。
更新:
我以为我可以在 expect 中使用的包装函数中调用 fn
三次,如下所示:
it('should throw LIMITED error', async () => {
const key = '
expect(async () => {
await fn(key)
await fn(key)
await fn(key)
}).toThrowError('LIMITED')
}
但即使这样也不会抛出 LIMITED
错误。
我什至在 fn
中添加了 console.log
以查看它是否被调用,但是当我将 fn
放入其中时它不会打印任何内容expect
中的包装函数。
所以我现在很想知道在尝试测试函数时 expect 是如何工作的。
最佳答案
toThrowError
断言使用 try..catch
运行提供的函数,这是捕获导致异常的代码段中的错误的唯一方法。
被拒绝的 promises 应该用 rejects
断言,而不是 toThrowError
,因为 async
函数实际上从不抛出错误。它是 promise 的语法糖,它会在抛出错误时返回被拒绝的 promise。 throw new Error(...)
在 async
中使用时与 return Promise.reject(new Error(...))
对应.
async () => {
await fn(key)
await fn(key)
await fn(key)
}
不能被认为是一个好的测试函数,因为它是松散的并且不能精确地测试哪个调用预计会导致错误。
它可能应该是:
...
await fn(key)
await fn(key)
await expect(fn(key)).rejects.toMatch('LIMITED')
关于node.js - jest 是否运行用于测试 "toThrowError"的包装函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54128449/