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("should be able to mock DOM call", function() {
spyOn($("#Something"), 'val').andReturn("bar");
result = $("#Something").val();
expect(result).toEqual("bar");
});
In my specrunner.html I have:
<input type="hidden" id="Something" value="foo" />
Unfortunately the spec fails with:
should be able to mock DOM call Expected ‘foo’ to equal ‘bar’.
This line is wrong:
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.
…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.
…is an existing object.
…is not an existing object – it is the result of a jQuery selector.
This will work: