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

我有这样的错误:

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

现在我想写一个testing来检查这个在预期的时候抛出:

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

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

正如你已经发现,你的代码执行引发错误的function, should没有机会赶上它。

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

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