javascript 使用 Mocha/Chai 测试 JS 异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18925884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:42:30  来源:igfitidea点击:

Testing JS exceptions with Mocha/Chai

javascriptcoffeescriptmochachai

提问by TheDelChop

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:

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

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?

我在这里做错了什么?

回答by Idan Wender

Either pass the function:

要么传递函数

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

Or use an anonymous function:

或者使用匿名函数

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

See the documentation on the throwmethodto learn more.

请参阅有关该throw方法文档以了解更多信息。

回答by plalx

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 thiskeyword inside the function I guess you could also just pass manager.testwithout binding it.

如果您知道您没有this在函数内部使用关键字,我想您也可以直接通过manager.test而不绑定它。

Also, your test name doesn't reflect what the code does. If it doesn't permet the construction of new instances, manager = new window.VisualizationsManagershould fail.

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