Spying on JQuery Selectors in Jasmine

前端 未结 6 1439
执念已碎
执念已碎 2020-12-02 15:29

I am unit testing some JavaScript with Jasmine and wish to spy on (mock) an element of the DOM that is accessed by a jQuery selector.

My spec is:

it(         


        
6条回答
  •  無奈伤痛
    2020-12-02 16:00

    I think there is a change in my jasmine version (2.0.3), hence the solution by Alex York didn't work as is, but definitely gave me a path. So here is the working spec jquery code which is to be tested

    $('someSelector').data('someAttribute').enable();
    

    here is the jasmine spec part of it

    var mockJqueryObject = { enable:function(){},disable:function(){}};
    //this mocks the .data('someAttribute') in above code.
    spyOn($.fn, "data").and.returnValue(mockSelectBoxObject); 
    

    A more granular spec could use another level of mock as

    spyOn(mockJqueryObject,"enable")
    spyOn(mockJqueryObject,"disable")
    

提交回复
热议问题