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

时间:2015-11-20 20:00:34

标签: javascript node.js mocha should.js

我有一个错误:

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'方式是什么?

1 个答案:

答案 0 :(得分:6)

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

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

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