【发布时间】:2015-12-28 15:42:32
【问题描述】:
我目前正在用 Javascript 构建一个石头剪刀布游戏,并使用 TDD 来指导我的代码。我正在尝试运行 Jasmine 测试,强制我的一个函数返回一个设定值。我希望我的“compChoice”函数从“选择”数组 [“Rock”、“Paper”、“Scissors”] 中返回一个随机元素,并且在我的测试中希望将其设置为“Rock”。我的测试如下。
describe("Game", function() {
var game;
beforeEach(function(){
game = new Game();
});
describe('user choice', function(){
it('should equal the choice the user selected', function(){
game.userSelect("Rock");
expect(game.userChoice).toEqual("Rock")
});
})
describe('draw', function(){
it('should equal true if user choice and comp choice are the same', function() {
game.userSelect("Rock");
spyOn(game,'compChoice').and.returnValue("Rock");
expect(game.opponentChoice).toEqual("Rock")
// expect(game.draw).toEqual(true);
});
})
});
当我的测试返回 “Expected ' ' to equal 'Rock'”时,我可以看出我的 spyOn 有问题。
我不知道为什么它没有像我问的那样调用间谍并将值设置为“Rock”。
我的实际代码如下供参考:
function Game() {
this.choices = ["Rock","Paper","Scissors"];
this.userChoice = "";
this.opponentChoice = "";
}
Game.prototype.userSelect = function(choice){
this.userChoice = choice;
}
Game.prototype.compChoice = function(){
this.opponentChoice = this.choices[Math.floor(Math.random()*this.choices.length)];
return this.opponentChoice;
}
【问题讨论】:
标签: javascript jasmine stub spy