繁体   English   中英

如何为依赖于外部服务的Angular $资源存根响应?

[英]How do I stub a response for an Angular $resource that depends on an external service?

如何存根响应而不是查询依赖于外部服务的$ resource? 我收到一个错误: Error: Unexpected request: GET data/counties.json

这是我的服务:

angular.module('myApp.services', ['ngResource']).
  factory("geoProvider", function($resource){
    return {
      states: $resource('data/states.json', {}, {
        query: {method: 'GET', params: {}, isArray: false}
      }),
      counties: $resource('data/counties.json', {}, {
        query: {method: 'GET', params: {}, isArray: false}
      })
   };
});

规格:

describe('service', function() {
  beforeEach(module('myApp.services'));

    describe('geoProvider', function() {
    it('should return data / JSON', inject(function(geoProvider){
      var data = geoProvider.counties.query();
     expect(data).toBe(some);
    }));

  });
});

您可以在测试中注入$ httpBackend并将其配置为期望您需要的请求:

describe('service', function() {
    var $httpBackend;

    beforeEach(module('myApp.services'));

    beforeEach(inject(function(_$httpBackend_) {
        $httpBackend = _$httpBackend_;
    }));

    it('should return data / JSON', inject(function(geoProvider){
        $httpBackend.expectGET('yoururl').respond({/* the response object */});

        var data = geoProvider.counties.query();

        $httpBackend.flush();

        expect(data).toBe(some);
    }));
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM