【问题标题】:Testing JS exceptions with Mocha/Chai [duplicate]使用 Mocha/Chai 测试 JS 异常 [重复]
【发布时间】:2013-09-26 09:06:56
【问题描述】:

尝试使用 Mocha/Chai 测试一些引发异常的代码,但没有运气,这是我要测试的简单代码:

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

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

Failure/Error: Oh no

我在这里做错了什么?

【问题讨论】:

    标签: javascript coffeescript mocha.js chai


    【解决方案1】:

    可能是因为你正在执行该函数,所以测试框架无法处理错误。

    尝试类似:

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

    如果你知道你没有在函数中使用 this 关键字,我猜你也可以直接传递 manager.test 而不绑定它。

    另外,您的测试名称并不能反映代码的作用。如果它不支持新实例的构建,manager = new window.VisualizationsManager 应该会失败。

    【讨论】:

      【解决方案2】:

      要么传递函数

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

      使用匿名函数

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

      请参阅documentation on the throw method 了解更多信息。

      【讨论】:

      • 这应该是 IMO 的最佳答案
      猜你喜欢
      • 1970-01-01
      • 2018-03-06
      • 2017-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      相关资源
      最近更新 更多