Mocking $(document) and $(window)

864 views
Skip to first unread message

Perry Smith

unread,
Jan 10, 2013, 11:37:21 PM1/10/13
to jasmi...@googlegroups.com
I have a function hooked to the window scroll event:

    function myScrollFunction(event) {
        console.log(event);
        var window_height = $(window).height();
        var document_scroll = $(document).scrollTop();
        var all_trs = $('table.upd_apar_defs tbody tr');
        var last_tr = $(all_trs[all_trs.length - 1]);
        var tr_height = last_tr.height();
        var o = last_tr.offset();
        var top = o.top;
       
        if ((window_height + document_scroll) > (top - (100 * tr_height))) {
            $(window).off('scroll', myScrollFunction);
            $.when( $.get(next_page_url(), null, null, 'json') )
                .done(load_succ)
                .fail(load_fail);
        }
    };

This is implementing an endless page feature.  I could redo the function into two functions $(document).scrollTop and $(window).height() being passed into the 2nd and then just test the 2nd function.  But I'm wondering if jQuery's "$" can be mocked.  I have jasmine-jquery but it does not provide mocking of $ (or jQuery).

A short while back I saw someone saying that if it is hard to test, then its not good code.  I've already refactored the code a bit to make load_succ and load_fail be functions I can spy on.  Do I need to continue this or is there an alternative?

Josef Biehler

unread,
Feb 26, 2013, 5:33:27 AM2/26/13
to jasmi...@googlegroups.com
My Code:
####
        function spyOn$() {
            var spy = spyOn(window, '$');

            for (var i in jQuery) {
                if (jQuery.hasOwnProperty(i)) $[i] = jQuery[i];
            }

            return spy;
        }

        jQuery = spyOn$().andCallFake(function (selector) {
            switch (selector) {
                case "#popupDiv":
                    return popupDiv;
                    break;
                case popupDiv:
                    return popupDiv;
#####

the "popupDiv" is a own MockObject that simulates some Attributes of a real HTML Div.
Of course that DivMock must also implement all the Methods offered by jQuery and used in your code.
With my code you have to develope a MockObject that simulates the scrollTop()

the spyOn$ Method was posted in this group it is neccessary to avoid loosing all the properties from jQuery
Reply all
Reply to author
Forward
0 new messages