【问题标题】:how can I assert throw when `new constructor()` with mocha and chai如何在使用 mocha 和 chai 的`new constructor()` 时断言 throw
【发布时间】:2016-08-07 00:31:32
【问题描述】:

如何正确投掷?对于同一个函数,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>

【问题讨论】:

    标签: javascript class ecmascript-6 chai throw


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 2018-06-26
    • 2023-03-04
    • 2016-05-08
    • 1970-01-01
    • 2012-07-16
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多