2017-09-17 53 views
1

我是新来的茉莉花和间谍的事情,希望你能指出正确的方向。正在使用spyOn()而没有可能的方法吗?

我有一个我想与单元测试覆盖的事件侦听器:

var nextTurn = function() { 
    continueButton.addEventListener("click", displayComputerSelection) 
}; 

nextTurn(); 

的总体思路是,以窥探“displayComputerSelection”功能。

it ("should call fn displayComputerSelection on continueButton click", function(){ spyOn(displayComputerSelection); continueButton.click(); expect(displayComputerSelection).toHaveBeenCalled();

由于间谍的基本结构是spyOn(<object>, <methodName>)我得到回应No method name supplied。 我试过试用jasmine.createSpy,但无法使其工作。 我将如何替换预期的方法?

回答

0

你的问题

在你的情况下,整个问题是如何或在哪里被定义displayComputerSelection,因为这是FUNC你想与你的间谍,以替换。

jasmine.createSpy()

这是你想要jasmine.createSpy()。例如,以下是您如何使用它的例子 - 完全未经测试 - 没有双关语意图。

var objectToTest = { 
    handler: function(func) { 
    func(); 
    } 
}; 

describe('.handler()', function() { 
    it('should call the passed in function', function() { 
    var func = jasmine.createSpy('someName'); 

    objectToTest.handler(func); 

    expect(func.calls.count()).toBe(1); 
    expect(func).toHaveBeenCalledWith(); 
    }); 
}); 
+0

非常感谢! 'displayComputerSelection'是一个全局变量,所以我发现我只需要使用'window'作为一个对象。 所以它这样工作: 'spyOn(window,“displayComputerSelection”);'' –

0

在我的特定情况下的答案是:

it ("should call displayComputerSelection on continueButton click", function(){ 
    spyOn(window, "displayComputerSelection"); 
    start(); //first create spies, and only then "load" event listeners 
    continueButton.click(); 
    expect(window.displayComputerSelection).toHaveBeenCalled(); 
}); 

浏览器似乎全局变量/函数挂接到“窗口”对象,因此它是在被窥探。

相关问题