8

I'm using Chai.should and I need to test for an exception, but whatever I try, I cannot get it to work. The docs only explain expect :(

I have this Singleton class which throws an error if you try

new MySingleton();

Here is the constructor that throws the error

constructor(enforcer) {
    if(enforcer !== singletonEnforcer) throw 'Cannot construct singleton';
    ...

Now I would like to check that this happens

 it('should not be possible to create a new instance', () => {
    (function () {
        new MySingleton();
    })().should.throw(Error, /Cannot construct singleton/);
 });

or

new MySingleton().should.throw(Error('Cannot construct singleton');

None of these work. How is this done ? Any suggestions ?

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333
  • 2
    This question is not a duplicate. It is asking about the `subject.should.throw` style. The other question is for the `expect` style. – Raul Santelices Jan 11 '18 at 16:56

2 Answers2

13

I know this is an answered question, but i'd still like to throw in my two cents.

There is a section in the style guide for this, namely: http://chaijs.com/guide/styles/#should-extras. So what does this look like in practice:

should.Throw(() => new MySingleton(), Error);

It's not all that different from the accepted answer, i find it a bit more readable though, and more in line with their guideline.

N. Tosic
  • 131
  • 2
  • 3
  • I believe this is the way to go, so I would mark this as accepted to help people. This is much more like chai style, I liked it. Especially when it comes to argument passing, this way is way more cleaner. – meakgoz Mar 20 '19 at 13:00
12

The Problem here is that you are executing the function directly, effectively preventing chai from being able to wrap a try{} catch(){} block around it.

The error is thrown before the call even reaches the should-Property.

Try it like this:

 it('should not be possible to create a new instance', () => {
   (function () {
       new MySingleton();
   }).should.throw(Error, /Cannot construct singleton/);
});

or this:

MySingleton.should.throw(Error('Cannot construct singleton');

This lets Chai handle the function call for you.

David Losert
  • 4,652
  • 1
  • 25
  • 31
  • 4
    Just want to add, if anyone is looking to pass parameters to the function, you can do `myfunc.bind(foo, bar).should.throw(...)`. – Raul Santelices Jan 11 '18 at 17:02