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>
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With