如何在$(window).on(" load",function(){})中测试代码;在Jasmine [英] How to test code inside $(window).on("load", function() {}); in Jasmine
问题描述
我有一个javascript,它在页面加载时附加DIV并在3秒后隐藏它。
I have a javascript below, which appends a DIV on page load and hides it after 3 sec.
var testObj = {
initialize: function() {
var that = this;
$(window).on("load", function() {
(function ($) { //Append Div
$('body').append("<div>TEST</div>");
})(jQuery);
that.hideAppendedDiv();
});
},
hideAppendedDiv: function() { //Hide appended Div after 3s
setTimeout(function(){
$("div").hide();
}, 3000);
}
};
//call Initialize method
testObj.initialize();
如何为代码中的方法编写Jasmine测试用例。
How to write Jasmine test cases for the methods in the code.
推荐答案
我猜你真的不想测试一个Javascript函数,比如 $(window).on('load ')...
,但你自己的函数 hideAppendedDiv()
从$(window).on('load')调用get。此外,您希望确保函数 hideAppendedDiv()
也可以。
I'm guessing that you don't really want to test a Javascript function such as $(window).on('load')...
, but that your own function hideAppendedDiv()
get's called from $(window).on('load'). Furthermore, you want to make sure that the function hideAppendedDiv()
works as well.
IMO,你需要两个预期。
IMO, you need two expects.
在你的设置之前的某个地方,每个函数:
Somewhere in your setup beforeEach function:
beforeEach(function () {
spyOn(testObj , 'hideAppendedDiv').and.callThrough();
});
预期
it('expects hideAppendedDiv() to have been called', function () {
// make the call to the initialize function
testObj.initialize ();
// Check internal function
expect(testObj.hideAppendedDiv).toHaveBeenCalled();
});
it('expects hideAppendedDiv() to hide div', function () {
// make the call to the hideAppendedDiv function
testObj.hideAppendedDiv();
// Check behavior
expect(... check the div ...)
});
修改
为了清楚起见, Jasmine 按顺序执行所有预期。现在,如果您有两个函数 fn_1()
,并且 fn_2()
并且您想要测试它们是否被调用为了你可以设置另一个spi函数,它返回一个特定的值,或每次调用时的一系列顺序和增量值。
Just to be clear, Jasmine executes all the expects in order. Now, if you have two functions fn_1()
, and fn_2()
and you want to test that they were called in order you can setup yet another spi function that returns a specific value, or a sequential and incremental set of values every time it is called.
beforeEach(function () {
spyOn(testObj , 'fn_1').and.returnValues(1, 2, 3);
spyOn(testObj , 'fn_2').and.returnValues(4, 5, 6);
});
第一次调用fn_1时,它将返回1,fn_2将返回4。
The first time fn_1 is called it will return 1, respectively fn_2 will return 4.
这只是其中一种方式,但你必须在测试时发挥创意。
That is just one of the ways, but you have to get creative when testing.
现在,如果你想测试一下在x时间后调用函数此处是已经解释过的帖子。
Now if you want to test that a function was called after x amount of time here is a post that already explains it.
这篇关于如何在$(window).on(" load",function(){})中测试代码;在Jasmine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!