如何使用使用自己的XMLHttpRequest而不是$http的库来测试服务

How to test service using library that uses its own XMLHttpRequest instead of $http

本文关键字:http 服务 测试 何使用 自己的 XMLHttpRequest      更新时间:2023-09-26

我得到了一个像

这样的angular服务
function userService() {
  // A library provide methods that not used $http service and not $.ajax either
  this.lib = theLib;
  // This one will invoke "api/v1/user"
  this.getAllUser = function () {
     return lib.getAll();
  }
}

如何测试

下面的这些函数
it('should return all user', function () {
   // How can I mock the returned data without using $http
   userService.getAllUser();
})

如果使用$http或$ajax,那么我可以模拟使用$httpBackend或模拟ajax的返回,这可能会很容易。还有另一种方法来模拟theLib,但它里面有很多方法,但我不认为这是一个好主意。对这种情况有什么建议吗?

在Jasmine 2.0中,引入了一个用于测试ajax的新API。

这是

的链接

您可以这样做,在每次测试之前设置stib ajax并在每次测试之后卸载它,您可以参考上面的链接了解更多信息

beforeEach(function() {
  jasmine.Ajax.install();
  jasmine.Ajax.stubRequest('YOUR_URL_HERE').andReturn({
    responseText: 'YOUR_RAW_STUBBED_DATA_HERE'
  });
});
afterEach(function() {
 jasmine.Ajax.uninstall();
});
it('My Ajax Test', function() {
 // . . . code that makes an ajax request . . .
})

对于XHR请求,您可以尝试这样做

beforeEach(function() {
 // spyOn(XMLHttpRequest.prototype, 'open').andCallThrough(); // Jasmine 1.x
  spyOn(XMLHttpRequest.prototype, 'open').and.callThrough(); // Jasmine 2.x
  spyOn(XMLHttpRequest.prototype, 'send');
});
 it("should return all user", function() {
    userService.getAllUser();
    expect(XMLHttpRequest.prototype.open).toHaveBeenCalled();
  });