Testing JS exceptions with Mocha/Chai [duplicate]

风流意气都作罢 提交于 2019-11-27 17:14:20

问题


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?


回答1:


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.




回答2:


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 throw method to learn more.



来源:https://stackoverflow.com/questions/18925884/testing-js-exceptions-with-mocha-chai

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!