javascript - 创建新实例的测试函数

标签 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
}

测试.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);
    });
  });
});

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

最佳答案

我不会模拟 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>

关于javascript - 创建新实例的测试函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48841201/

相关文章:

java - 获取无法解析引用本地 ejb-ref 未实现父接口(interface)

javascript - 如何在 aws cognito 中创建不同的访问级别?

调用非静态方法的Java静态引用变量

javascript - Object.create 而不是构造函数进行继承

java - 将对象转换为日期

jquery - 引用 DOM jQuery DOM 对象时使用变量

java - 将 Dagger 组件存储在静态字段中

c++ - C++ 中构造函数注入(inject)的高级配置

Javascript 捕获错过的按键事件

javascript - IE 中的宽度必须比 ff 和 ch 多 2 px