1

如何使用 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/

4

1 回答 1

2

尝试search像以下这样称呼您:

svc.user({user:'gigablox'}).search(function(user) {
    expect(user.testing).toEqual('anything');
});

原因是调用svc.user()返回带有search()方法的资源类对象。该search()方法使用 jsonp 发出请求。如果不调用该search()方法, $httpBackend 将看不到任何请求,因此您会看到问题中提到的错误。

于 2013-09-30T14:48:02.510 回答