使用Mocha/Chai测试JS异常

32

尝试使用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

我在这里做错了什么?

2个回答

46

要么通过该函数

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

或者使用匿名函数:

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

请查看throw方法的文档以了解更多信息。


这应该是我个人认为最好的答案。 - Arjan

29

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

尝试类似以下方式:

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

如果您知道函数内部没有使用this关键字,我想您也可以直接传递未绑定的manager.test

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接