简体   繁体   中英

Testing function that creates new instance

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM