测试JSONP $资源AngularJS [英] testing JSONP $resource AngularJS

查看:164
本文介绍了测试JSONP $资源AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何判断一个请求被发送并接收数据与JSONP服务?

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;
});

继GET请求的例子:

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:


  • 错误:没有挂起请求刷新

  • 错误:预约等待人数:JSONP

  • Error: No pending request to flush !
  • Error: Unsatisfied requests: JSONP

使用AngularJS 1.2和噶0.10.2

明白了在这里工作: http://jsfiddle.net/DhUqT/

推荐答案

试着打电话给你的搜索这样的:

Try to call your search like the following:

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

原因是调用 svc.user()返回与搜索资源类对象()方法。在搜索()方法使用JSONP做出请求。如果没有调用搜索()方法,$ httpBackend不会看到任何要求,所以你看在你的问题中提到的错误。

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.

这篇关于测试JSONP $资源AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆