Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fail a test with Chai.js

In JUnit you can fail a test by doing:

fail("Exception not thrown"); 

What's the best way to achieve the same using Chai.js?

like image 337
Sionnach733 Avatar asked Nov 17 '15 11:11

Sionnach733


People also ask

What is done () in Chai?

notify(done) is hanging directly off of . should , instead of appearing after a promise assertion. This indicates to Chai as Promised that it should pass fulfillment or rejection directly through to the testing framework.

What is chai used for in testing?

Chai is an assertion library that is mostly used alongside Mocha. It can be used both as a BDD / TDD assertion library for NodeJS and can be paired with any JavaScript testing framework. It has several interfaces that a developer can choose from and looks much like writing tests in English sentences.

Should I assert vs vs expect?

Note expect and should uses chainable language to construct assertions, but they differ in the way an assertion is initially constructed. In the case of should , there are also some caveats and additional tools to overcome the caveats. var expect = require('chai').


2 Answers

There's assert.fail(). You can use it like this:

assert.fail(0, 1, 'Exception not thrown'); 
like image 157
Dmytro Shevchenko Avatar answered Sep 21 '22 09:09

Dmytro Shevchenko


There are many ways to fake a failure – like the assert.fail() mentioned by @DmytroShevchenko –, but usually, it is possible to avoid these crutches and express the intent of the test in a better way, which will lead to more meaningful messages if the tests fail.

For instance, if you expect a exception to be thrown, why not say so directly:

expect( function () {     // do stuff here which you expect to throw an exception } ).to.throw( Error ); 

As you can see, when testing exceptions, you have to wrap your code in an anonymous function.

Of course, you can refine the test by checking for a more specific error type, expected error message etc. See .throw in the Chai docs for more.

like image 26
hashchange Avatar answered Sep 18 '22 09:09

hashchange