测试简单 Ajax- 成功回调

Test simple Ajax- Success Callback

我正在尝试测试这个简单的 Ajax-Jasmine 请求:

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));

我做错了什么?谢谢!

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);
    });
});

你能试着改变一下吗

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

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

还有单元测试Ajax,像这样在jasmine beforeEach 和afterEach 中使用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, "comment": "Hey there" }]');

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