使用should.js和Mocha检查抛出新错误

Checking for a throw new Error with should.js and Mocha

本文关键字:新错误 错误 js should Mocha 检查 使用      更新时间:2023-09-26

我抛出了一个错误,如下所示:

if (somethingBadHappened) {
    throw new Error('what were you thinking, batman?')
}

现在我想写一个测试来检查这是否在预期的时候抛出:

should(MyClass.methodThatShouldThrow()).throws('what were you thinking, batman?')

但这实际上造成了错误。我做错了什么?js的文档应该很轻,因为它继承了assert.throws,但即使是它的文档也不能以"Should.js"的方式工作吗?

正如您所发现的,您的代码执行的函数会抛出错误&should没有机会抓住它。

为了允许正确的断言,您需要将函数调用包装在一个匿名函数中。

should(function ()  {MyClass.methodThatShouldThrow();} ).throw('what were you thinking, batman?')