n92 n92 - 6 months ago 29
jQuery Question

How to test code inside $(window).on("load", function() {}); in Jasmine

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();


How to write Jasmine test cases for the methods in the code.

Answer

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, you need two expects.

Somewhere in your setup beforeEach function:

beforeEach(function () {
    spyOn(testObj , 'hideAppendedDiv').and.callThrough();
});

Expectations

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 ...) 
});

Edit


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);
});

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.

Now if you want to test that a function was called after x amount of time here is a post that already explains it.

Comments