Mocha 默认使用来自 node.js (https://nodejs.org/api/assert.html) 的 Assert。您不需要任何外部库来检查方法是否引发错误。
Assert 有一个方法 - assert.throws,它有三个参数,但这里只有两个真正重要:
- 函数 - 这里传递函数,不是函数调用
- 错误 - 此处传递或对象构造函数或函数用于检查错误
假设您有一个名为sendMessage(message) 的函数,它在未设置消息参数时抛出错误。功能代码:
function sendMessage(message) {
if (!message || typeof message !== 'string') {
throw new Error('Wrong message');
}
// rest of function
}
好的,所以为了测试它,你需要额外的函数来覆盖输入。为什么?因为assert.throws 不给任何机会向要测试的函数传递参数。
所以不是
// WRONG
assert.throws(sendMessage, Error); // THIS IS WRONG! NO POSSIBILITY TO PASS ANYTHING
你需要创建匿名函数:
// CORRECT
assert.throws(() => {
sendMessage(12); // usage of wanted function with test parameters
}, Error)
你能看出区别吗?我没有直接传递函数,而是将函数调用放在匿名函数中,目的是使用准备好的输入调用它。
第二个参数呢。这取决于应该抛出什么样的错误,在上面的例子中Error对象被抛出,所以我不得不把Error放在那里。在此操作的结果中,assert.throws 比较抛出的对象是否是相同类型的对象。如果不是Error 会抛出不同的东西,那么这部分需要更改。例如,我将抛出 String 类型的值,而不是 Error。
function sendMessage(message) {
if (!message || typeof message !== 'string') {
throw 'Wrong message'; // change to String
}
// rest of function
}
现在是测试调用
assert.throws(() => {
sendMessage(12); // usage of wanted function with test parameters
}, (err) => err === 'Wrong message')
我使用比较函数代替第二个参数中的Error,以便将抛出的错误与预期进行比较。