测试创建新实例的功能

时间:2018-02-17 12:20:55

标签: javascript object dependency-injection jasmine mocking

如果我创建一个在新实例中存储状态的函数,我该如何模拟该实例构造函数,或者我是否需要这样做?

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

另外,有没有更好的方法来测试它是否进入数组,例如查看实例的内容以验证它是什么?

1 个答案:

答案 0 :(得分:1)

我不会嘲笑Score,因为它不是外部呼叫,并且它没有任何看起来需要被嘲笑的行为。 GameScore现在都只存储状态,并且很容易按原样进行测试。

是的,您可以深入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>
&#13;
&#13;
&#13;