[英]Testing function that creates new instance
如果我创建一个在新实例中存储状态的函数,我该如何模拟该实例构造函数,或者我是否需要这样做?
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
因为它不是外部调用,而且它没有任何看起来需要模拟的行为。 Game
和Score
现在都只存储状态,这很容易按原样进行测试。
是的,您可以像这样深入研究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.