Reputation: 885
If I create a function that stores state in an new instance, how can I mock that instance constructor or do I need to do that at all?
function Game() {
this.scoreArray = []
}
Game.prototype.addScore = function(number) {
score = new Score(number);
this.scoreArray.push(score);
};
function Score(number){
this.number = number
}
test.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);
});
});
});
Also, is there a better way of testing that it goes into the array, such as looking at the contents of the instance to verify that it is what it is?
Upvotes: 1
Views: 47
Reputation: 5671
I would not mock Score
because it's not an external call and it doesn't have any behavior that looks like it needs to be mocked. Both Game
and Score
only store state right now, and that's easy to test as-is.
And yes, you can dive into the scoreArray
to test its members like this.
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>
Upvotes: 1