如何使用mocha和chai断言当`new Construction tor()`时抛出

人气:439 发布:2022-10-16 标签: javascript class throw chai ecmascript-6

问题描述

我怎样才能正确投掷?对于同一个函数,抛出和不抛都会通过测试

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构造函数之一引发错误。扔其他任何东西通常都是不受欢迎的。

739