2016-04-15 40 views
3

我怎么能正确地抛出?它是有线的,对于相同的功能,既not.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>

回答

2

.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/); 

注: BTW,使用Error构造函数之一抛出一个错误。抛出别的东西通常都会被人忽视。

+0

谢谢!有用! – Sabrina

+0

如果有帮助,您可能需要考虑[接受此答案](http://meta.stackexchange.com/a/5235/235416):-) – thefourtheye

+0

谢谢,刚学会如何接受答案。 :) – Sabrina