How to test for thrown error with Chai.should
<p>I'm using <a href="http://chaijs.com/api/bdd/" rel="noreferrer">Chai.should</a> and I need to test for an exception, but whatever I try, I cannot get it to work. The <a href="http://chaijs.com/api/bdd/#method_throw" rel="noreferrer">docs</a> only explain <code>expect</code> :(</p>

<p>I have this Singleton class which throws an error if you try</p>

<pre><code>new MySingleton();
</code></pre>

<p>Here is the constructor that throws the error</p>

<pre><code>constructor(enforcer) {
    if(enforcer !== singletonEnforcer) throw 'Cannot construct singleton';
    ...
</code></pre>

<p>Now I would like to check that this happens</p>

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

<p>or</p>

<pre><code>new MySingleton().should.throw(Error('Cannot construct singleton');
</code></pre>

<p>None of these work. How is this done ? Any suggestions ?</p>