4

我在使用 Jasmine BDD 框架执行 ajax 时遇到了麻烦。

我想测试实际的 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,它永远不会进入成功函数。

我究竟做错了什么?

4

3 回答 3

2

回答我自己的问题。Jasmine 中的 Ajax 调用需要异步。如果您不想更改代码以进行测试,您可以使用 ajaxSetup 将 async 的默认值设置为 false

it("getsetting", function () {
  $.ajaxSetup({
    async:false
  });
  expect(getUserSetting(101,0)).toBe('30');
});
于 2011-09-26T09:33:11.173 回答
1

虽然将 async 设置为 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);
     });    
  });
});
于 2011-10-31T09:12:03.677 回答
0

我了解到您想使用 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”

于 2012-12-29T21:06:36.330 回答