[英]Testing function that creates new instance
如果我創建一個在新實例中存儲狀態的函數,我該如何模擬該實例構造函數,或者我是否需要這樣做?
function Game() {
this.scoreArray = []
}
Game.prototype.addScore = function(number) {
score = new Score(number);
this.scoreArray.push(score);
};
function Score(number){
this.number = number
}
測試.js
describe("#Game", function() {
beforeEach(function() {
game = new Game();
describe("#addScore", function() {
it("adds an instance of a score object into scoreArray", function() {
game.addScore(5);
game.addScore(2);
var arrayLength = game.scoreArray.length;
expect(arrayLength).toEqual(2);
});
});
});
另外,是否有更好的方法來測試它是否進入數組,例如查看實例的內容以驗證它是什么?
我不會嘲笑Score
因為它不是外部調用,而且它沒有任何看起來需要模擬的行為。 Game
和Score
現在都只存儲狀態,這很容易按原樣進行測試。
是的,您可以像這樣深入研究scoreArray
以測試其成員。
describe("#Game", function() { beforeEach(function() { game = new Game(); }); describe("#addScore", function() { it("adds an instance of a score object into scoreArray", function() { game.addScore(5); game.addScore(2); var arrayLength = game.scoreArray.length; expect(arrayLength).toEqual(2); expect(game.scoreArray[0].number).toEqual(5); expect(game.scoreArray[1].number).toEqual(2); }); }); }); function Game() { this.scoreArray = [] } Game.prototype.addScore = function(number) { score = new Score(number); this.scoreArray.push(score); }; function Score(number){ this.number = number }
<link href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.0.0/jasmine.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.0.0/jasmine.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.0.0/jasmine-html.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/3.0.0/boot.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.