简体   繁体   English

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

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

I've got an error thrown like so: 我有这样的错误抛出:

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

Now I want to write a test to check that this throws when expected: 现在,我想编写一个测试来检查是否在期望时抛出该异常:

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

But that actually throws the error. 但这实际上引发了错误。 What am I doing wrong? 我究竟做错了什么? Should.js docs are pretty light, since it inherits from assert.throws , but even the docs for that doesn't work in the 'should.js' way? Should.js文档非常轻巧,因为它继承自assert.throws ,但是即使该文档也无法以“ should.js”方式运行?

As you had found out, your code execute the function which throws the error & should doesn't get a chance to catch it. 如您所知,您的代码执行了引发错误的函数,并且should没有机会抓住它。

To allow proper assertion, you need to wrap the function call in an anonymous function. 为了允许正确的断言,您需要将函数调用包装在匿名函数中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM