Mocha/Chai:使用错误消息测试抛出的错误
Mocha/Chai: testing thrown Errors with error message
这是 this question 的后续问题:
我不仅要测试函数是否抛出错误,还要测试抛出的错误是否具有相同的错误消息。
所以我尝试了:
expect(Person.getPerson.bind(Person, id)).to.throw(new Error(`Person ${id} not found`));
在 getPerson 函数中抛出一个错误,如下所示:
if (!isPersonExistent(id)) {
throw new Error(`Person ${id} not found`);
}
并且给定的消息如下所示:
AssertionError: expected [Function: bound getPerson] to throw 'Error: Person 1 not found' but 'Error: Person 1 not found' was thrown
我猜这与两个错误对象是两个不同的对象有关。但是我还如何测试它们是否有相同的错误消息。最好一步到位。
试试这个:
try {
Person.getPerson(id);
} catch (error) {
expect(error.message).to.be('Error: Person 1 not found');
return;
}
expect.fail('Should have thrown');
您的断言失败是正确的,因为 Chai .throw
正在通过严格相等比较错误对象。来自 the spec:
When one argument is provided, and it’s an error instance, .throw
invokes the target function and asserts that an error is thrown that’s strictly (===
) equal to that error instance.
同样的规格说明:
When two arguments are provided, and the first is an error instance or constructor, and the second is a string or regular expression, .throw
invokes the function and asserts that an error is thrown that fulfills both conditions as described above.
哪里
.throw
invokes the target function and asserts that an error is thrown with a message that contains that string.
所以测试所需行为的方法是使用两个参数,如下所示:
expect(Person.getPerson.bind(Person, id)).to.throw(Error, `Person ${id} not found`);
这是 this question 的后续问题:
我不仅要测试函数是否抛出错误,还要测试抛出的错误是否具有相同的错误消息。 所以我尝试了:
expect(Person.getPerson.bind(Person, id)).to.throw(new Error(`Person ${id} not found`));
在 getPerson 函数中抛出一个错误,如下所示:
if (!isPersonExistent(id)) {
throw new Error(`Person ${id} not found`);
}
并且给定的消息如下所示:
AssertionError: expected [Function: bound getPerson] to throw 'Error: Person 1 not found' but 'Error: Person 1 not found' was thrown
我猜这与两个错误对象是两个不同的对象有关。但是我还如何测试它们是否有相同的错误消息。最好一步到位。
试试这个:
try {
Person.getPerson(id);
} catch (error) {
expect(error.message).to.be('Error: Person 1 not found');
return;
}
expect.fail('Should have thrown');
您的断言失败是正确的,因为 Chai .throw
正在通过严格相等比较错误对象。来自 the spec:
When one argument is provided, and it’s an error instance,
.throw
invokes the target function and asserts that an error is thrown that’s strictly (===
) equal to that error instance.
同样的规格说明:
When two arguments are provided, and the first is an error instance or constructor, and the second is a string or regular expression,
.throw
invokes the function and asserts that an error is thrown that fulfills both conditions as described above.
哪里
.throw
invokes the target function and asserts that an error is thrown with a message that contains that string.
所以测试所需行为的方法是使用两个参数,如下所示:
expect(Person.getPerson.bind(Person, id)).to.throw(Error, `Person ${id} not found`);