使用 Mocha/Chai 测试 JS 异常
尝试使用 Mocha/Chai 测试一些引发异常的代码,但没有运气,这是我尝试测试的简单代码:
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:
class window.VisualizationsManager
test: ->
throw(new Error 'Oh no')
这是我的测试:
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
我在这里做错了什么?
推荐答案
可能是因为你正在执行该函数,所以测试框架无法处理错误.
It's probably because you are executing the function right away, so the test framework cannot handle the error.
尝试类似:
chai.expect(manager.test.bind(manager)).to.throw('Oh no')
如果你知道你没有在函数中使用 this
关键字,我猜你也可以直接传递 manager.test
而不绑定它.
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.
另外,您的测试名称并不能反映代码的作用.如果它不支持新实例的构建,manager = new window.VisualizationsManager
应该会失败.
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.
相关文章