使用 Mocha/Chai 测试 JS 异常 [英] Testing JS exceptions with Mocha/Chai

查看:25
本文介绍了使用 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 异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆