Jquery Jasmine测试这样一个场景:在发出新请求之前中止以前的ajax请求,并在中止后将其分配回null

Jquery Jasmine测试这样一个场景:在发出新请求之前中止以前的ajax请求,并在中止后将其分配回null,jquery,ajax,jasmine,Jquery,Ajax,Jasmine,我有一个实时搜索的场景,在创建一个新的请求之前,我需要中止先前挂起的ajax请求。虽然我已经写了下面的代码,它工作得很好 App.MyNamespace.xhr = null; App.MyNamespace.makeAjaxRequest = function() { if (App.MyNamespace.xhr) { App.MyNamespace.xhr.abort(); App.MyNamespace.xhr = null; } App.MyNamespace.xhr

我有一个实时搜索的场景,在创建一个新的请求之前,我需要中止先前挂起的ajax请求。虽然我已经写了下面的代码,它工作得很好

App.MyNamespace.xhr = null;
App.MyNamespace.makeAjaxRequest = function() {
if (App.MyNamespace.xhr) {
    App.MyNamespace.xhr.abort();
    App.MyNamespace.xhr = null;
 }
App.MyNamespace.xhr = $.ajax({
    type: "GET",
    url: "test.html",
    data: "query",
    });
};
我正试图为同一个场景编写一个Jasmine测试,我需要测试我的ajax请求调用abort并将ajax请求分配回null的两种场景。下面是我的测试用例

describe('#makeAjaxRequest', function() {
  describe('aborts previous ajax request', function() {
    beforeEach(function() {
      App.MyNamespace.xhr = jasmine.createSpyObj('App.MyNamespace.xhr', ['abort']);
      App.MyNamespace.makeAjaxRequest();
     });

    it('calls abort on ajax request', function() {
      expect(App.MyNamespace.xhr.abort).toHaveBeenCalled();
    });

    it('assigns ajax request to null', function() {
      expect(App.MyNamespace.xhr).toBeNull();
    });
   });
});
现在,在上面的测试用例中,第二条it语句,即“将ajax请求分配给null”通过,但第一条it语句,即“调用ajax请求时中止”失败,并出现以下错误

失败/错误:TypeError:“null”不是对象(正在评估“App.MyNamespace.xhr.abort”)

我的假设是jasmine只是在检查最后一条语句,我们在调用myAjaxRequest函数时将其赋值为null。但是,如果我没有在实际函数中将App.MyNamespace.xhr请求分配回null,那么第一条it语句“calls abort on ajax request”就会通过

describe('#makeAjaxRequest', function() {
  describe('aborts previous ajax request', function() {
    var xhr;

    beforeEach(function() {
      App.MyNamespace.xhr = jasmine.createSpyObj('App.MyNamespace.xhr', ['abort']);
      xhr = App.ModalSearch.xhr;
      App.MyNamespace.makeAjaxRequest();
    });

    it('calls abort on ajax request', function() {
      expect(xhr.abort).toHaveBeenCalled();
    });

    it('assigns ajax request to null', function() {
      expect(App.MyNamespace.xhr).toBeNull();
    });
  });
});

我们如何测试这种情况,在这种情况下,我可以测试两个it语句,即它应该在ajax请求上调用abort,并将ajax请求分配回null。

解决方案是在调用App.MyNamespace.makeAjaxRequest()函数之前将App.MyNamespace.xhr分配给一个变量

describe('#makeAjaxRequest', function() {
  describe('aborts previous ajax request', function() {
    var xhr;

    beforeEach(function() {
      App.MyNamespace.xhr = jasmine.createSpyObj('App.MyNamespace.xhr', ['abort']);
      xhr = App.ModalSearch.xhr;
      App.MyNamespace.makeAjaxRequest();
    });

    it('calls abort on ajax request', function() {
      expect(xhr.abort).toHaveBeenCalled();
    });

    it('assigns ajax request to null', function() {
      expect(App.MyNamespace.xhr).toBeNull();
    });
  });
});