问题
How do I test a request being sent and data is being received with a JSONP service?
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;
});
Following the GET request examples:
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();
});
});
I can't seem to get by some errors:
Error: No pending request to flush !Error: Unsatisfied requests: JSONP
Using AngularJS 1.2 and Karma 0.10.2
Edit
Got it working here: http://jsfiddle.net/DhUqT/
回答1:
Try to call your search like the following:
svc.user({user:'gigablox'}).search(function(user) {
expect(user.testing).toEqual('anything');
});
The reason is the call to svc.user() returns a resource class object with a search() method. The search() method uses jsonp to make request. Without calling the search() method, $httpBackend will not see any request, so you see the errors mentioned in your question.
来源:https://stackoverflow.com/questions/19096300/testing-jsonp-resource-angularjs