【问题标题】:spyOn function in Jasmine that returns random element from arrayJasmine 中的 spyOn 函数,它从数组中返回随机元素
【发布时间】: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


    【解决方案1】:

    看起来你还没有调用 spied 方法。您在 spy 中定义调用函数时会发生什么,因此在您的情况下

    spyOn(game,'compChoice').and.returnValue("Rock");
    

    您已经定义,游戏对象中的函数 compChoice 应该被监视,并且当它被调用时,它应该返回“Rock”值。在下一行你确实期望

     expect(game.opponentChoice).toEqual("Rock")
    

    所以你在这里检查对象属性 opponentChoice 是否设置为 "Rock" 但是你错过了调用方法compChoice,它应该设置opponentChoice 的值。你应该粘贴这个

    game.compChoice();
    

    在您的代码中的 spyOn 和期望之间。

    已编辑:

    好的,现在我知道发生了什么。 Spy 正在为 compChoice 方法创建一个模拟。但这只是一个模拟,您定义这个模拟应该返回“Rock”值。但实际上这个模拟函数不像普通的 compChoice 方法那样工作。所以它不会将对手选择值分配给游戏对象。它只返回您定义的“Rock”值。

    它看起来也有点奇怪,因为它不是单元测试。它更像是集成测试。您正在尝试测试这些方法如何协同工作。所以我认为 Jasmine 不适合这种测试。但是,如果您真的想测试这种行为,您可以通过以下方式使用 callFake 方法:

    spyOn(game,'compChoice').and.callFake(function(){
    
                  game.opponentChoice = "Rock";
                  return "Rock";
    });
    

    通过这种方式,您调用了假函数,该函数也分配了 opponenChoice 值。

    【讨论】:

    • 这个答案对您有帮助吗?
    • 很抱歉没有回复阿图尔,感谢您的回答!我已经离开所以无法回应。我尝试了您推荐的方法并在 Spy 之后调用了 compChoice() 函数,但它没有奏效。当我 console.log(game.opponentChoice) 它没有返回任何东西时,我本来希望 Rock 因为 SpyOn 而被返回。
    • 我用解释编辑了我之前的答案,为什么它不起作用
    猜你喜欢
    • 2016-05-12
    • 2023-04-06
    • 2012-04-25
    • 1970-01-01
    • 2019-12-10
    • 2020-08-28
    • 1970-01-01
    • 2016-11-03
    • 2015-08-22
    相关资源
    最近更新 更多