我了解到您想使用 jasmine 编写集成测试,这要归功于 jasmine 的异步支持,我希望以下示例可以帮助您了解如何使用 jasmine 的异步特性来编写实际的集成测试:
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的限制, 并且您的服务器必须根据响应的一部分返回标头“Access-Control-Allow-Origin:your requesting domain”