如何使用jasmine-ajax验证send方法已被调用?

时间:2019-04-10 19:57:56

标签: javascript ajax jasmine jasmine-ajax

如果我从不调用jasmine-ajax方法,应该onreadystatechange调用readyState为4的send吗?

如果上述不是预期的行为,如何使用jasmine-ajax验证是否调用了send方法?

这是正在测试的代码:

    Loader = (function() {

      var loadNames = function(url, success_callback, error_callback) {

        var ajax = new XMLHttpRequest();

        ajax.open("GET", url);
        ajax.onreadystatechange = function () {
          console.log("Ready state is " + ajax.readyState);
          if (ajax.readyState === 4 && ajax.status === 200) {
            success_callback(JSON.parse(ajax.responseText));
          } else if (ajax.readyState === 4 && ajax.status !== 200) {
            error_callback("There was a problem. Status returned was " + ajax.status);
          }
        };

        ajax.onerror = function () {
         error_callback("Unknown error");
        };

        // Shouldn't removing the call to send prevent
        // onredystatechange from being called with readyState 4?
        // ajax.send();
      };

      return {
        loadNames: loadNames
      };

    })();

这是测试:

describe("Loader", function () {

  var successFunction, failFunction;

  beforeEach(function () {
    jasmine.Ajax.install();
    successFunction = jasmine.createSpy("successFunction");
    failFunction = jasmine.createSpy("failFunction");
  });

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

  describe("#loadNames", function () {    
    it("Makes a success callback with the data when successful", function () {
      Loader.loadNames("someURL", successFunction, failFunction);
      jasmine.Ajax.requests.mostRecent().respondWith({
        "status": 200,
        "contentType": 'application/json',
        "responseText": '[1, 2, 4, 3, 5]'
      });

      // Shouldn't this fail since I never called send?
      expect(successFunction).toHaveBeenCalledWith([1, 2, 4, 3, 5]);
    });
  });
});

我很惊讶地看到successFunction被调用,因为被测代码从未调用过ajax.send()。如果这是库的预期行为,那么如何spyOn基础ajax对象,以便可以验证测试中的代码调用了send

1 个答案:

答案 0 :(得分:1)

是的,您没有调用ajax.send(),但是由于这段代码而触发了ajax.onreadystatechange事件:

jasmine.Ajax.requests.mostRecent().respondWith({
  "status": 200,
  "contentType": 'application/json',
  "responseText": '[1, 2, 4, 3, 5]'
});

更改就绪状态并将就绪状态设置为完成。实际上,正如文档中也指出的那样:https://jasmine.github.io/2.6/ajax.html

关于如何检查xhr.send是否真正被调用的问题,此SO answer解释了您可以在beforeEach中执行以下操作来监视它:

spyOn(XMLHttpRequest.prototype, 'send');

取消注释加载程序中的xhr.send()部分后,您可以检查以下方法调用:

describe("#loadNames", function () {    
  it("Makes a success callback with the data when successful", function () {
    Loader.loadNames("someURL", successFunction, failFunction);
    jasmine.Ajax.requests.mostRecent().respondWith({
      "status": 200,
      "contentType": 'application/json',
      "responseText": '[1, 2, 4, 3, 5]'
    });

    expect(XMLHttpRequest.prototype.open).toHaveBeenCalled();
  });
});