当使用 mocha 和 chai 的 `new constructor()` 时,我如何断言抛出

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

怎样才能正确投掷?对于相同的功能,thrownot.throw 都通过了测试

代码也可以在 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。你应该调用它来做实际的断言。实际上,您只是获得函数对象。

你可能想试试

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

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

注意: 顺便说一句,使用 Error 构造函数之一抛出错误。扔任何其他东西通常是不受欢迎的。