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 异常


基础教程推荐
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01