javascript 使用 Mocha/Chai 测试 JS 异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18925884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Testing JS exceptions with Mocha/Chai
提问by TheDelChop
Trying to test some code that throws an exception with Mocha/Chai, but having no luck, here's the simple code I'm trying to test:
尝试测试一些使用 Mocha/Chai 引发异常的代码,但没有运气,这是我正在尝试测试的简单代码:
class window.VisualizationsManager
test: ->
throw(new Error 'Oh no')
Here is my test:
这是我的测试:
describe 'VisualizationsManager', ->
it 'does not permit the construction of new instances', ->
manager = new window.VisualizationsManager
chai.expect(manager.test()).to.throw('Oh no')
However, when I run the spec, the test fails and throws the exception.
但是,当我运行规范时,测试失败并抛出异常。
Failure/Error: Oh no
what am I doing wrong here?
我在这里做错了什么?
回答by Idan Wender
Either pass the function:
要么传递函数:
chai.expect(manager.test).to.throw('Oh no');
Or use an anonymous function:
或者使用匿名函数:
chai.expect(() => manager.test()).to.throw('Oh no');
See the documentation on the throw
methodto learn more.
请参阅有关该throw
方法的文档以了解更多信息。
回答by plalx
It's probably because you are executing the function right away, so the test framework cannot handle the error.
这可能是因为您正在立即执行该函数,因此测试框架无法处理该错误。
Try something like:
尝试类似:
chai.expect(manager.test.bind(manager)).to.throw('Oh no')
If you know that you aren't using the this
keyword inside the function I guess you could also just pass manager.test
without binding it.
如果您知道您没有this
在函数内部使用关键字,我想您也可以直接通过manager.test
而不绑定它。
Also, your test name doesn't reflect what the code does. If it doesn't permet the construction of new instances, manager = new window.VisualizationsManager
should fail.
此外,您的测试名称并不反映代码的作用。如果它不符合新实例的构建,则manager = new window.VisualizationsManager
应该失败。