如何使用 JSONP 服务测试正在发送的请求和正在接收的数据?
angular.module('search', [])
.factory('SearchService', function($q,$rootScope,$resource) {
var _search = {};
_search.user = function(opts){
return $resource('https://api.github.com/users/:user', {user: opts.user}, {
search: {method:'JSONP',params:{callback: 'JSON_CALLBACK'}}
});
}
return _search;
});
按照 GET 请求示例:
describe('search tests', function () {
var svc, httpBackend;
beforeEach(function (){
module('ngResource');
module('search');
inject(function($httpBackend, SearchService) {
svc = SearchService;
httpBackend = $httpBackend;
});
});
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
it('should send the message and return the response', function (){
var returnData = { testing: 'anything'};
httpBackend.expectJSONP('https://api.github.com/users/gigablox?callback=JSON_CALLBACK').respond(returnData);
svc.user({user:'gigablox'}, function(user) {
expect(user.testing).toEqual('anything');
});
httpBackend.flush();
});
});
我似乎无法解决一些错误:
Error: No pending request to flush !
Error: Unsatisfied requests: JSONP
使用 AngularJS 1.2 和 Karma 0.10.2
编辑
在这里工作:http: //jsfiddle.net/DhUqT/