Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing JS exceptions with Mocha/Chai [duplicate]

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?

like image 586
TheDelChop Avatar asked Sep 20 '13 21:09

TheDelChop


People also ask

What is Mocha and Chai testing?

Mocha is a JavaScript test framework running on Node. js and in the browser. Mocha allows asynchronous testing, test coverage reports, and use of any assertion library. Chai is a BDD / TDD assertion library for NodeJS and the browser that can be delightfully paired with any javascript testing framework.


2 Answers

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.

like image 99
Idan Wender Avatar answered Sep 22 '22 12:09

Idan Wender


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.

like image 23
plalx Avatar answered Sep 21 '22 12:09

plalx