Testing JS exceptions with Mocha/Chai(使用 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.
这篇关于使用 Mocha/Chai 测试 JS 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Mocha/Chai 测试 JS 异常
基础教程推荐
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在for循环中使用setTimeout 2022-01-01