Jasmine 在没有方法的情况下使用spyOn()是否可行?
我对茉莉花和间谍的事还不熟悉,希望你能指出正确的方向 我想在单元测试中介绍一个事件侦听器:Jasmine 在没有方法的情况下使用spyOn()是否可行?,jasmine,spyon,Jasmine,Spyon,我对茉莉花和间谍的事还不熟悉,希望你能指出正确的方向 我想在单元测试中介绍一个事件侦听器: var nextTurn = function() { continueButton.addEventListener("click", displayComputerSelection) }; nextTurn(); 总体思路是监视“displayComputerSelection”功能 it(“应调用fn displayComputerSelection on continueBu
var nextTurn = function() {
continueButton.addEventListener("click", displayComputerSelection)
};
nextTurn();
总体思路是监视“displayComputerSelection”功能
it(“应调用fn displayComputerSelection on continueButton click”,函数(){
spyOn(显示计算机选择);
continueButton.click();
期望(displayComputerSelection).tohaveBeenCall();
由于间谍的基本结构是spyOn(,)
我得到一个响应没有提供方法名
。
我试过用jasmine.createSpy做实验,但没能成功。
我将如何替换预期的方法?您的问题 在您的场景中,整个问题是如何或在何处定义
displayComputerSelection
,因为您希望用spy替换此函数
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();
});
});
在我的具体案例中,答案是:
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();
});
浏览器似乎将全局变量/函数连接到“窗口”对象,因此可以监视它。非常感谢!
displayComputerSelection
是一个全局变量,所以我发现我只需要使用window
作为对象。因此它的工作方式是:spyOn(窗口,“displayComputerSelection”);