Spying on JQuery Selectors in Jasmine

前端 未结 6 1440
执念已碎
执念已碎 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 15:57

    This line is wrong:

    spyOn($("#Something"), 'val').andReturn("bar");
    

    Jasmine's spyOn function expects two parameters. The first is an existing object. The second is a function name as a string. You are correctly passing in the function name as a string ("val") but you are not passing in an existing object as the first parameter.

    $("#Something")
    

    ...is not an existing object. It is the result (the return value) of a jQuery selector. More specifically, it will return a jQuery object representing the matched nodes - kind of like an array of results.

    $
    

    ...is an existing object.

    $.fn
    

    ...is an existing object.

    $("#Something")
    

    ...is not an existing object - it is the result of a jQuery selector.

    This will work:

    it("should be able to mock DOM call", function () {
        //spyOn($.fn, "val").andReturn("bar"); //pre-jasmine 2.0 syntax
        spyOn($.fn, "val").and.returnValue("bar"); //Jasmine 2.0 Syntax
        var result = $("#Something").val();
        expect(result).toEqual("bar");
    });
    

提交回复
热议问题