2013-08-02 59 views
4

我發現Sinon不會讓你存根屬性,只有方法。我試圖找出如何處理/擁抱這個。我應該如何避免使用Sinon.js的存根屬性

我有以下代碼:

var Player = { 
    addPoints: function(points) { 
    this.score += points; 
    }, 
    score: 0 
} 

var Game = { 
    setPlayers: function(players) { 
    this.players = players; 
    }, 
    over: function() { 
    return this.players.some(function(player) { 
     return player.score >= 100; 
    }); 
    }, 
} 

這裏有一個測試,我寫道:

describe("Game", function() { 
    it("is over if a player has at least 100 points", function() { 
    var game = Object.create(Game); 
    player = Object.create(Player); 
    game.setPlayers([player]); 
    player.addPoints(100); 
    game.over().should.be.true; 
    }); 
}); 

感覺錯了我一定要進去,並呼籲addPoints()Player當我測試Game。我最初的本能是存根Player.points,但我不能這樣做,因爲Sinon只存根屬性,而不是方法。

我應該如何思考這個問題?

回答

2

你不需要存根game.points只需設置它。所以你可以創建一個簡單的模擬Game,這只是一個object持有間諜的setPlayer方法。然後您可以在測試中設置score以滿足您的需求。

describe("Game", function() { 
    var game; 

    before(function(){ 
    game = {addPoints: jasmine.createSpy()} 
    }) 

    it("is over if a player has at least 100 points", function() { 
    game.score = 100; 
    player = Object.create(Player); 
    game.setPlayers([player]); 
    game.over().should.be.true; 
    }); 
}); 
+0

謝謝 - 這在回顧過程中顯得很明顯。 – michael

6

我通過電子郵件發送的SinonJS郵件列表,作者回信:

就像你做的事。直接寫入分數屬性 完全違背了addPoints方法的目的,並且使得您的 測試與實現緊密耦合(從而使其變得脆弱)。

如果你確實想「存根」的屬性,方法如下:它

describe("Game", function() { 
    it("is over if a player has at least 100 points", function() { 
    var game = Object.create(Game); 
    player = Object.create(Player); 
    game.setPlayers([player]); 
    player.score = 100; 
    game.over().should.be.true; 
    }); 
}); 

對實例的屬性 - 在太聰明約 它沒有任何意義。我仍然建議你不要這樣做。