Ajax没有用Jasmine执行

Ajax没有用Jasmine执行

问题描述:

我有用Jasmine BDD框架执行ajax的麻烦。Ajax没有用Jasmine执行

我想测试实际的ajax调用,而不是做出假的响应。我已阅读文档并尝试了所有内容,但似乎忽略了ajax代码。我也尝试过使用间谍,但它似乎没有帮助。

不工作一个非常简单的例子:

describe("A jQuery ajax test", function() { 
    it("should make AJAX request", function() { 
    expect(testAjax()).toBe(1); 
    }); 
}); 

function testAjax() { 
    var ret=0 
    $.ajax({ 
    type: "GET", 
    url: "obj.json", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function(data){ret=1;} 
    }); 
    return ret; 
} 

返回始终为0,它从来没有进入成功的功能。

我在做什么错?

+0

有人有一个可以成功执行Ajax与Ajax共享的示例项目吗? – a2011

解答我自己的问题。 Jasmine中的Ajax调用需要是异步的。如果你不想改变你的代码,能够测试它,你可以使用ajaxSetup设置dafault值异步为假

it("getsetting", function() { 
    $.ajaxSetup({ 
    async:false 
    }); 
    expect(getUserSetting(101,0)).toBe('30'); 
}); 

在设置异步为false解决这个问题它通常不是一种选择在大多数Web应用程序中,因为整个页面在ajax调用期间将被锁定。

我会将回调函数传递给testAjax()方法,当您从Web服务获得响应时将执行该方法。然后你可以在你的回调中做出断言(期望)。

它应该是这个样子:

function testAjax(callback) { 
    var ret=0 
    $.ajax({ 
    type: "GET", 
    url: "obj.json", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function(data){ 
     callback(ret); 
    }, 
    error:function(){ 
     callback(ret); 
    } 
    }); 
} 

describe("A jQuery ajax test", function() { 
    it("should make AJAX request", function() { 
    testAjax(function(ret){ 
     expect(ret).toBe(1); 
    });  
    }); 
}); 
+1

问题是,如果我没有异步:false,Ajax调用永远不会完成... – a2011

我明白,你想编写使用茉莉一个集成测试,这是异步的支持很可能要感谢的是茉莉花有,我希望下面的例子将有助于您了解如何使用Jasmine的Async功能编写实际的集成测试:

describe("A jQuery ajax test", function() { 

it("should make AJAX request", function() { 
var return = null; 


runs(function(){ 
// hosts actual ajax call 
     return = testAjax(); 
}); 

waitsFor(function(){ 
//this method polls until the condition is true or timeout occurs,whichever occurs first 
return return.readyState==4; 
},"failure message",700//timeout in ms 
); 

runs(function(){ 
// 2nd runs block can be used to verify the actual change in state 
// Add other relevant expectation according to your application context. 
     expect(return).toBeTruthy(); 

}); 

}); 

});

function testAjax() { 
// result here is a deffered object whose state can be verified in the test 
var result = null; 
result = $.ajax({ 
    type: "GET", 
    url: "obj.json", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    success: function() { //do something on success} 
    }); 
return ret; 
}​ 

请注意:运行AJAX调用你会被Cross-origin_resource_sharing加以限制,您的服务器必须返回按照响应头“访问控制允许来源:您的请求域”的一部分