I wrote a helper function that takes an array of id / value pairs.
var jasminTestHelper = { spyOnValAndFake : function(obj) { var i, j; spyOn($.fn, 'val').andCallFake(function() { for ( i = 0, j = obj.length; i < j; i++) { if (this.selector === '#' + obj[i][0]) { return obj[i][1]; } } }) } }
Each pair tells the faker function for which id whose value should be returned if the jQuery-val () function is called using the id selector. It is used as follows:
jasminTestHelper.spyOnValAndFake([["id1", "value1"], ["id2", "value2"]]);
If $('#id1').val() is called in the function being tested, the fake function returns value1 , if $('#id2').val() , it returns value2 . Therefore, you do not need to bother with the DOM, you just mock the jQuery-val () function and model the return values. Other jQuery functions can probably mock the same way.
Roland WΓΌrth Jan 25 '13 at 20:07 2013-01-25 20:07
source share