如何对在jasmine中触发Ajax调用的函数进行单元测试

时间:2017-09-28 01:26:15

标签: unit-testing jasmine karma-jasmine

例如像

这样的东西
func do something()
{
api.ajax('') //Ajax call that triggers inside the function
.done(response){
do something with response
}
}

如何从响应中得到一些东西并做出我的断言?任何帮助都会非常有帮助!提前谢谢!

1 个答案:

答案 0 :(得分:0)

在测试中使用jasmine-ajax看起来像这样:

describe('Sample test', function(){

    var request = function(arg){
        return new Promise(function(resolve, reject){
            $.ajax({
                method:'GET',
                url: 'example.com/api/'+arg,
                success: function(response){
                    resolve(changeResponse(response));
                },
                error: reject
            });
        });

        function changeResponse(response){
            return response.key + '-changed';
        }
    };

    var TestResponses = {
        someEndPoint: {
            success: {
                status: 200,
                responseText: '{"key":"value"}'
            }
        }
    };

    beforeEach(function(){
        jasmine.Ajax.install();
    });

    afterEach(function(){
        jasmine.Ajax.uninstall();
    });

    it('can be called with for some end-point', function(){
        spyOn($, 'ajax');
        request('something');
        expect($.ajax).toHaveBeenCalled();
        var actualAjaxOptions = $.ajax.calls.mostRecent().args[0];
        expect(actualAjaxOptions).toEqual(jasmine.objectContaining({
            method:'GET',
            url: 'example.com/api/something',
        }));
    });

    it('modifies response as expected', function(done){
        request('something').then(function(){
            expect(arguments[0]).toEqual('value-changed');
            done();
        }, function(reason){
            done.fail();
        });
        jasmine.Ajax.requests.mostRecent().respondWith(TestResponses.someEndPoint.success);
    });
})

请注意:

  

jasmine-ajax目前与任何使用的库兼容   XMLHttpRequest的。用jQuery和Zepto测试。

(来自docs