测试简单的Ajax-成功回调

时间:2015-01-18 23:21:25

标签: javascript jquery ajax jasmine

我正在尝试使用Jasmine测试这个简单的Ajax-Request:

var Card = {
    single : function(params){
        $.ajax({
            dataType: "json",
            headers: {"X-TOKEN": TOKEN},
            url: SERVER,
            success: function(data,status,xhr){
                params.params['card'] = data['card'];
                params.callback(params.params); 
            },
            error: function(xhr, status, error) {
                    ErrorHandler.connection(xhr,status,error);
            }
        });
    },

我的测试代码:

       it("should call Callback with appropiate Callbacks", function(){
            var Meth = {test_method: function(params){}};
            spyOn(Meth,"test_method");
            spyOn($, "ajax").and.callFake(function(e) {
                 e.success('one','two','three');
            });
            Card.single({id: 2, params: {callback: Meth.test_method}});
            expect(Meth.test_method).toHaveBeenCalled();
        });

我根本无法理解为什么我的测试不起作用!相反,我得到一个未定义的错误:

 Uncaught TypeError: undefined is not a function

在Jasmine Libary的这行中jasmine.js 2108:

this.result.failedExpectations.push(this.expectationResultFactory(data));

我错了什么?谢谢!

2 个答案:

答案 0 :(得分:0)

spy.and.callFake()将委托对函数的调用,而不是原来的函数。 http://jasmine.github.io/2.1/introduction.html#section-Spies:_ and.callFake

没有ajax调用的示例失败

describe('test', function () {
    it("should call Callback with appropiate Callbacks", function(){
        var called = false;
        var Meth = {test_method: function(params){
            called = true;
        }};
        spyOn(Meth,"test_method").and.callFake(function(){
        });
        Meth.test_method();
        expect(Meth.test_method).toHaveBeenCalled();
        expect(called).toBe(true);
    });
});

传递没有ajax调用的示例

describe('test', function () {
    it("should call Callback with appropiate Callbacks", function(){
        var called = false;
        var Meth = {test_method: function(params){
        }};
        spyOn(Meth,"test_method").and.callFake(function(){
            called = true;
        });
        Meth.test_method();
        expect(Meth.test_method).toHaveBeenCalled();
        expect(called).toBe(true);
    });
});

答案 1 :(得分:0)

您可以尝试更改

吗?
params.params['card'] = data['card'];
params.callback(params.params);

params.params['card'] = data['card'];
params.params.callback(params.params);  

另外,为了对Ajax进行单元测试,通常更容易在beforeEach和afterEach之类的jasmine中使用sinon(http://sinonjs.org/docs/#server)。

beforeEach(function() {
    this.server = sinon.fakeServer.create();
  });

afterEach(function() {
  this.server.restore();
 });

在你的测试中你可以嘲笑这样的电话

this.server.requests [0] .respond(200,{" Content-Type":" application / json"},                                  ' [{" id":12,"评论":"嘿那里" }]&#39);

最后,您可以检查您的间谍,看看它是否被调用