如果将参数传递给fetch,则使用jasmine进行BackboneJS测试

时间:2012-04-11 10:11:17

标签: backbone.js jasmine

我有一个Backbone Collection,我需要将一些参数传递给.fetch({data:{gender:'male'}})。有没有办法用jasmine测试参数是否通过?

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以通过使用下面示例中的方法来实现这一点。 请注意,以下代码将拦截fetch-call并返回,该呼叫将无法到达服务器。如果您想进行服务器端仿真,那么您需要使用Sinon或其他类似的方法。

    describe("People collection" function() {
        var people = Backbone.Collection.extend({
            // ...
        });

        function searchPeople(people, data ) {
            people.fetch(data);
        }

        it("must verify the fetch parameters!", function(){
            var param = {data : {gender : 'male'}};
            // Set up the spy.
            spyOn(people, 'fetch').andReturn(); // Warning: this makes the call synchronous, Fetch actually won't go through!

            // Now perform the operation that would invoke Collection.fetch.
            searchPeople(people, param);

            expect(people.fetch).toHaveBeenCalled();            // Verifies the fetch was actually called.
            expect(people.fetch).toHaveBeenCalledWith(param);   // Verifies that the fetch was called with specified param.

        });
    });