如何使用使用自己的XMLHttpRequest而不是$http的库来测试服务
How to test service using library that uses its own XMLHttpRequest instead of $http
我得到了一个像
这样的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();
});
相关文章:
- $http服务未触发成功或错误回调
- Http服务工厂将未定义的返回到Angular中的控制器
- 在http服务单元测试中使用request-js时,chai.request不是一个函数
- Angular $http 服务不加载 json 文件
- 在 angularJs 中从控制器调用同时$http服务
- Angular 中的 HTTP 服务将 POST 数据作为请求正文的键发送,没有值
- AngularJS$http服务中的encodeURIComponent
- 从服务器获取数据,并使用$http服务和ng-change在select事件上显示它
- 如何在AngularJS中动态更改$http服务URL
- 如何在Angular中设置异步HTTP服务的回调,以便在不定义数组的情况下在控制器中填充数组
- Angular-使用httpBackend测试http服务会引发意外异常
- 如何在有角度的$http服务请求中将JSONP指定为dataType
- 使用$http服务将数据发布到本地 json 文件时未发现错误
- ES6 发电机与$http服务
- Angular JS:在HTTP服务(POST)中传递输入参数
- 使用 angular 的 $http 服务来调用 js 文件
- AngularJS - 将then()与$http服务一起使用
- AngularJS$http服务中的调用,返回解析的数据,而不是承诺
- 如果可能的话,我应该使用 angularjs $http服务来处理请求还是 jquery ajax
- 如何将异常从 PHP 抛出到 Angular $http 服务