Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChaiJS expect constructor to throw error

I am trying to test that my constructor will throw an error using the Teaspoon gem for Rails, with ChaiJS as my assertion library.

When I run the following test:

  it('does not create the seat if x < 0', function() {
    var badConstructor = function() {
      return new Seat({ radius: 10, x: -0.1, y: 0.2, seat_number: 20, table_number: 30});
    };

    expect(badConstructor).to.throw(Error, 'Invalid location');
  });

I get this output:

Failures:

  1) Seat does not create the seat if x < 0
     Failure/Error: undefined is not a constructor (evaluating 'expect(badConstructor).to.throw(Error(), 'Invalid location')')

The constructor is throwing the error, but I think I am not writing the test properly.

When I try running expect(badConstructor()) then I get the output:

Failures:

  1) Seat does not create the seat if x < 0
     Failure/Error: Invalid location
like image 991
ThomYorkkke Avatar asked May 11 '15 19:05

ThomYorkkke


2 Answers

Had the same problem. Wrap your constructor with a function:

var fcn = function(){new badConstructor()};
expect(fcn).to.throw(Error, 'Invalid location');
like image 148
David Vargas Avatar answered Sep 30 '22 05:09

David Vargas


For test a throw message error inside a constructor, with mocha and chai you can write this test (with ES6 syntax):

'use strict';
// ES6 class definition
class A {
  constructor(msg) {
    if(!msg) throw new Error('Give me the message');
    this.message = msg;
  }
}

// test.js
describe('A constructor', function() {
  it('Should throw an error with "Give me the message" text if msg is null', function() {
    (() => new A()).should.throw(Error, /Give me the message/);
  });
});
See this Pen for check live working of above code zJppaj by Diego A. Zapata Häntsch (@diegoazh) on CodePen.
like image 32
Diego Alberto Zapata Häntsch Avatar answered Sep 30 '22 05:09

Diego Alberto Zapata Häntsch