How should I avoid stubbing properties with Sinon.js

I found that Sinon does not allow you to drown properties, but only methods. I am trying to figure out how to deal with this.

I have the following code:

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; }); }, } 

Here is the test I wrote:

 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; }); }); 

I am not good at going in and calling addPoints() on the Player when I test the Game . My initial instinct was to stub Player.points , but I cannot do this because Sinon only mutes properties, not methods.

How should I think about it?

+4
source share
2 answers

I emailed the SinonJS mailing list, and the author wrote:

Just like you did. Direct writing to the evaluation property completely affects the purpose of the addPoints method and the test is tightly coupled with the implementation (which makes it fragile).

If you really want to "drown" the property, here's how:

 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; }); }); 

This property is on the instance - there is nothing to do too smart This. I still recommend that you do not do it this way, though.

+6
source

You do not need to drown out game.points , just install it. This way you can create a simple layout for the Game , which is just an object containing a spy for the setPlayer method. and then you can set a score in the test for whatever you want.

 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; }); }); 
+2
source

Source: https://habr.com/ru/post/1494908/


All Articles