問(wèn)題描述
我正在編寫(xiě)一個(gè)簡(jiǎn)單的點(diǎn)擊處理程序,需要傳入事件(像這樣)
I'm writing a simple click handler and need the event passed in (like so)
Thing = function($){
var MyObject = function(opts){
this.opts = opts;
};
MyObject.prototype.createSomething = function(){
var that = this;
$('#some_dom_element').live('click', function(e) {
that.doStuff(e);
});
};
MyObject.prototype.doStuff = function(e) {
//do some javascript stuff ...
e.preventDefault();
};
return MyObject;
}(jQuery);
目前在我的 jasmine 規(guī)范中,我有一些東西可以監(jiān)視我期望被調(diào)用的函數(shù)(但是因?yàn)樗怯?e 調(diào)用的——不是沒(méi)有 args——我的斷言失敗了)
Currently in my jasmine spec I've got something to spy on the function I expect gets invoked (but since it's called with e -not without args- my assertion is failing)
it ("live click handler added to the dom element", function(){
var doSpy = spyOn(sut, 'doStuff');
sut.createSomething();
$("#some_dom_element").trigger('click');
expect(doSpy).toHaveBeenCalledWith();
});
如何更正此toHaveBeenCalledWith"以按預(yù)期工作?
How can I correct this "toHaveBeenCalledWith" to work as I expect?
更新
我無(wú)法按原樣獲得公認(rèn)的答案,但我可以稍微改變它,以下是我的 100% 工作示例
I couldn't get the accepted answer to work as is but I was able to alter it just a little and the below is my 100% working example
it ("should prevent default on click", function(){
var event = {
type: 'click',
preventDefault: function () {}
};
var preventDefaultSpy = spyOn(event, 'preventDefault');
sut.createSomething();
$("#some_dom_element").trigger(event);
expect(preventDefaultSpy).toHaveBeenCalledWith();
});
推薦答案
你必須觸發(fā)你自己的事件,為 stopPropagation
方法傳遞一個(gè)間諜,因?yàn)槟阆霚y(cè)試事件是否被停止.
You have to trigger your own event passing a spy for the stopPropagation
method, cause you wanna test if the event was stopped.
var event = {
type: 'click',
stopPropagation: function(){}
}
var spy = spyOn(event, 'stopPropagation');
$('#some_dom_element').trigger(event);
expect(spy).toHaveBeenCalled();
注意:當(dāng)您監(jiān)視要測(cè)試的對(duì)象時(shí),會(huì)產(chǎn)生代碼異味,因?yàn)槟_(kāi)始測(cè)試類(lèi)的內(nèi)部行為.把你的功能想象成一個(gè)黑盒子,只測(cè)試你放入和取出的東西.在您的情況下,重命名函數(shù)會(huì)破壞測(cè)試,而代碼仍然有效.
Note: there is code smell when you spy on the object you want to test, because you start to test the inner behavior of your class. Think about your function as a black box and test only the things you put in and get out. In your case, renaming the function in will break the test, while the code is still valid.
這篇關(guān)于如何斷言使用茉莉花點(diǎn)擊事件調(diào)用間諜?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!