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

余生颓废 提交于 2020-01-15 04:20:29

问题


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.


回答1:


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.




回答2:


You don't need to test the window load event, if you move the append code out of the anonymous function call and pass it into the event handler instead you can test the functionality in exactly the same way you would anything else and your code will be better structured.



来源:https://stackoverflow.com/questions/36401443/how-to-test-code-inside-window-onload-function-in-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!