简体   繁体   English

创建新实例的测试函数

[英]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测试.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.我不会嘲笑Score因为它不是外部调用,而且它没有任何看起来需要模拟的行为。 Both Game and Score only store state right now, and that's easy to test as-is. GameScore现在都只存储状态,这很容易按原样进行测试。

And yes, you can dive into the scoreArray to test its members like this.是的,您可以像这样深入研究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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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