Spying on JQuery Selectors in Jasmine

前端 未结 6 1455
执念已碎
执念已碎 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:55

    I wrote a helper-function, which accepts 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, which value should be returned if the jQuery-val()-function is called with the id-selector. It is used like this:

    jasminTestHelper.spyOnValAndFake([["id1", "value1"], ["id2", "value2"]]);
    

    If $('#id1').val() is called in your function under test, the fake-function returns value1, if $('#id2').val() is called it returns value2. So you don't need to fiddle with the DOM, you just mock the jQuery-val()-function and simulate return-values. Other jQuery-functions could probably mocked the same way.

提交回复
热议问题