用 Jasmine 模拟 jQuery ajax 调用

Loz*_*zer 0 ajax jquery unit-testing jasmine jasmine-ajax

我正在使用 Jasmine 2.5.2 为使用 jQuery 3.1.1 执行 Ajax 请求的代码编写单元测试。我想模拟 Ajax 调用,提供我自己的响应状态和文本。

我正在使用 Jasmine ajax 插件 ( https://github.com/pivotal/jasmine-ajax )。

按照https://jasmine.github.io/2.0/ajax.html上的示例,它使用 XMLHttpRequest 对象,效果很好。

describe("mocking ajax", function() {
    describe("suite wide usage", function() {
        beforeEach(function() {
            jasmine.Ajax.install();
        });

        afterEach(function() {
            jasmine.Ajax.uninstall();
        });

        it("specifying response when you need it", function() {
            var doneFn = jasmine.createSpy("success");

            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(args) {
                if (this.readyState == this.DONE) {
                    doneFn(this.responseText);
                }
            };

            xhr.open("GET", "/some/cool/url");
            xhr.send();
            expect(jasmine.Ajax.requests.mostRecent().url).toBe('/some/cool/url');
            expect(doneFn).not.toHaveBeenCalled();

            jasmine.Ajax.requests.mostRecent().respondWith({
                "status": 200,
                "contentType": 'text/plain',
                "responseText": 'awesome response'
            });
            expect(doneFn).toHaveBeenCalledWith('awesome response');                      
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

注意:这与记录的示例略有不同,必须更改jasmine.Ajax.requests.mostRecent().response()jasmine.Ajax.requests.mostRecent().respondWith().

当我使用 jQuery Ajax 时,doneFn 永远不会被调用。

describe("mocking ajax", function() {
    describe("suite wide usage", function() {
        beforeEach(function() {
            jasmine.Ajax.install();
        });

        afterEach(function() {
            jasmine.Ajax.uninstall();
        });

        it("specifying response when you need it", function() {
            var doneFn = jasmine.createSpy("success");

            $.ajax({
                method: "GET",            
                url: "/some/cool/url"})
            .done(function(result) {
                doneFn(result);
            });
            expect(doneFn).toHaveBeenCalledWith('awesome response');                      
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

茉莉花说

Jasmine-Ajax 在 XMLHttpRequest 对象模拟您的请求,因此应该与其他执行 ajax 请求的库兼容。

$.ajax 从 1.4.x 返回 jqXHR 而不是 XMLHttpRequest - 这是否会破坏对 Jasmine Ajax 的支持?

Win*_*ier 6

以下是您可以在茉莉花测试中模拟 ajax 的几种方法

方法一:

  • 使用模拟 ajax.js,您可以模拟文档中描述的全局 xhr 对象
  • 但是,您需要在成功函数上指定一个间谍并让它调用(如下面的代码所示)
  • 这里看到它的行动

    describe('ajax test suite', function() {
    
      beforeEach(function() {
        jasmine.Ajax.install();
      });
    
      afterEach(function() {
        jasmine.Ajax.uninstall();
      });
    
      it('sample test', function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(args) {
          if (this.readyState == this.DONE) {
            testObj.successFunction(this.responseText);
          }
        };
        spyOn(testObj, 'successFunction').and.callThrough();
        xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1");
        xhr.send();
        expect(jasmine.Ajax.requests.mostRecent().url).toBe('https://jsonplaceholder.typicode.com/posts/1');
        expect(testObj.successFunction).not.toHaveBeenCalled();
        jasmine.Ajax.requests.mostRecent().respondWith({
          "status": 200,
          "contentType": 'text/plain',
          "responseText": 'awesome response'
        });
        expect(testObj.successFunction).toHaveBeenCalledWith('awesome response');
      });
    });
    
    Run Code Online (Sandbox Code Playgroud)

方法B:

  • 直接模拟 $.ajax 对象。无论是 get/post/load 还是来自 jquery 的任何 ajax 风格,您可以简单地模拟 $.ajax,如下所示。

    var testObj = {
      ajaxFunction : function(url){     
       $.ajax({url : url}).done(this.successFunction.bind(this));
      },
      successFunction : function(data){
       console.log(data);
     }
    }
    
    describe('ajax test suite', function(){
        it('sample test', function(){
         testObj.ajaxFunction('https://jsonplaceholder.typicode.com/posts/1');
         spyOn($, 'ajax').and.callFake(function(e) {
              return $.Deferred().resolve({'text':'this a a fake response'}).promise();
         });
         spyOn(testObj, 'successFunction').and.callThrough();
         testObj.ajaxFunction('https://jsonplaceholder.typicode.com/posts/1');
         expect(testObj.successFunction).toHaveBeenCalledWith({'text':'this a a fake response'});
      });
    });
    
    Run Code Online (Sandbox Code Playgroud)