33

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?

Sionnach733
  • 4,686
  • 4
  • 36
  • 51

5 Answers5

65

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

assert.fail(0, 1, 'Exception not thrown');
Dmytro Shevchenko
  • 33,431
  • 6
  • 51
  • 67
  • 4
    ... and your answer is the right one in case there is no other option, so you get my upvote, too :) – hashchange Nov 17 '15 at 17:10
  • @hashchange There's one good example where you would use that instead of "to.throw" and that's in the case of where you might throw errors in object constructors. – Mayhem93 Dec 20 '16 at 21:46
36

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.

hashchange
  • 7,029
  • 1
  • 45
  • 41
15

Just try

expect.fail("custom error message");

or

should.fail("custom error message");

as decribed in chai docs : https://www.chaijs.com/api/bdd/#method_fail

Nigrimmist
  • 10,289
  • 4
  • 52
  • 53
4

I also stumbled that here was no direct fail(msg). For some time, I worked around with...

assert.isOk(false, 'timeOut must throw')

(Using this in places that should not be reachable, i.e. in promise-testing…)

Chai is compatible with standard ES6 errors, so this works:

throw new Error('timeOut must throw') 

…or, since assert itself is essentially the same as assert.isOK… my favourite is:

assert(false,'timeOut must throw')

…well, almost as short as assert.fail(….

Frank N
  • 9,625
  • 4
  • 80
  • 110
0

I did this way

const expect = require('chai').expect;
const exists = true;
expect(!exists).to.throw('Unknown request type');
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162