2016-04-15 41 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