testing JSONP $resource AngularJS

北城以北 提交于 2019-12-24 06:57:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!