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

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

我遇到了这样的错误:

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

现在我想编写一个测试来检查它是否按预期抛出:

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

但这实际上会引发错误。我究竟做错了什么? Should.js 文档非常简洁,因为它继承自 assert.throws,但即使是它的文档也不能以 'should.js' 的方式工作?

正如您所发现的,您的代码执行了抛出错误的函数,should 没有机会捕捉到它。

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

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