Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I assert throw when `new constructor()` with mocha and chai

how can I throw correctly? it's wired that for a same function, both throw and not.throw pass the test

code is also available on jsfiddle, https://jsfiddle.net/8t5bf261/

class Person {
  constructor(age) {
    if (Object.prototype.toString.call(age) !== '[object Number]') throw 'NOT A NUMBER'
    this.age = age;
  }
  howold() {
    console.log(this.age);
  }
}

var should = chai.should();
mocha.setup('bdd');

describe('Person', function() {
  it('should throw if input is not a number', function() {
    (function() {
      var p1 = new Person('sadf');
    }).should.not.throw;
    
    (function() {
      var p2 = new Person('sdfa');
    }).should.throw;

  })
})

mocha.run();
<div id="mocha"></div>
<link href="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.4.5/mocha.css" rel="stylesheet" />
<script src="https://cdn.rawgit.com/jquery/jquery/2.1.4/dist/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/2.4.5/mocha.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/3.5.0/chai.min.js"></script>
like image 1000
Sabrina Luo Avatar asked Apr 15 '16 07:04

Sabrina Luo


1 Answers

.throw is a function, as per the docs. You should call that to do the actual assertion. As it is, you are just getting the function object.

You might want to try

(function() {
  var p1 = new Person(1);
}).should.not.throw(/NOT A NUMBER/);

(function() {
  var p2 = new Person('sdfa');
}).should.throw(/NOT A NUMBER/);

Note: BTW, use one of the Error constructors to throw an Error. Throwing anything else is generally frowned upon.

like image 146
thefourtheye Avatar answered Sep 22 '22 16:09

thefourtheye