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

Sab*_*Luo 5 javascript class throw chai ecmascript-6

我怎样才能正确投掷?它是连线的,对于同一个函数,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();
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

the*_*eye 5

.throw是一个函数,根据文档。你应该调用它来做实际的断言。实际上,您只是在获取函数对象。

你可能想试试

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

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

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