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

查看:584
本文介绍了测试JS异常与Mocha / Chai的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试测试一些代码,在Mocha / Chai抛出异常,但没有运气,这里是我想测试的简单代码:

  class window.VisualizationsManager 

test: - >
throw(new Error'Oh no')

这是我的测试:

  describe'VisualizationsManager', - > 

it'不允许构建新实例', - >

manager = new window.VisualizationsManager

chai.expect(manager.test())to.throw('Oh no')



但是,当我运行规范时,测试失败并抛出异常。

 失败/错误:Oh no 

错误在这里?

解决方案

这可能是因为你正在执行的函数,所以测试框架不能处理的错误。 p>

尝试类似:

  chai.expect(manager.test.bind (经理))to.throw('哦no')

如果你知道你' t使用函数中的 this 关键字,我猜你也可以不通过绑定传递 manager.test p>

此外,您的测试名称并不反映代码的作用。如果它不允许新实例的构造, manager = new window.VisualizationsManager 应该失败。


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')

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?

解决方案

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.

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.

这篇关于测试JS异常与Mocha / Chai的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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