为什么Jest会在不应出现的时候抛出错误? [英] Why does Jest throw an error when it should not?
本文介绍了为什么Jest会在不应出现的时候抛出错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这样的功能:
const test = (match) => {
if (match !== 'cat') {
throw new TypeError()
}
}
我的测试是:
describe('test', () => {
it('must throw error'() => {
try {
test('cat')
catch(err){
expect(err).toStrictEqual(new TypeError())
}
}
}
但是测试通过了.它应该失败.为什么会通过?
But the test passed. It should fail. Why did it pass?
推荐答案
只有在未满足期望的情况下,测试才会失败.在您的情况下,因为不会引发任何错误,所以甚至不会评估任何期望.因此,测试通过了.
Tests only fail if there is an unmet expectation. In your case, because no error is thrown, no expectation is ever even evaluated. Therefore the test passes.
要解决此问题,请执行以下任一操作:
To deal with this, either:
-
确保使用
expect.assertions
:
make sure exactly one expectation is evaluated using
expect.assertions
:
describe('test', () => {
it('must throw error'() => {
expect.assertions(1);
try {
test('cat')
catch(err){
expect(err).toStrictEqual(new TypeError())
}
}
}
或
使用 .toThrow
期望来处理错误而不是自己捉住它:
handle the error with a .toThrow
expectation rather than catching it yourself:
describe('test', () => {
it('must throw error'() => {
expect(() => test('cat')).toThrow(TypeError)
}
}
请注意,如 Estus Flask
Note that, as Estus Flask pointed out, this can only assert on either the constructor or the message of the error.
这篇关于为什么Jest会在不应出现的时候抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文