【问题标题】:Unexpected request: GET No more request expected at $httpBackend意外请求:GET $httpBackend 不再有请求
【发布时间】:2013-11-15 18:26:41
【问题描述】:

我的作用域中有一个函数可以在用户单击按钮时检索我的服务状态,或者 当某个事件被触发并自动调用该函数时。

这是我的函数,在我使用的控制器中定义:

$scope.getStatus = function() {
  $http({method: 'GET', url: config.entrypoint + config.api + '/outbound/service/' + $scope.serviceId})
    .success(function(data) {
      $scope.errorMessage = '';
      $scope.serviceAllGood = data;
    })
    .error(function() {
      $scope.serviceAllGood = '';
      $scope.errorMessage = 'We are experiencing problems retrieving your service status.';
    });
  }

单元测试如下:

describe('SendServiceCtrl', function(){
    var scope, ctrl, $httpBackend, configuration;

    beforeEach(function () {
      module('papi', 'ngUpload');
    });

    beforeEach(inject(function(_$httpBackend_, $rootScope, $controller, config) {
      configuration = config;
      $httpBackend = _$httpBackend_;
      $httpBackend.expectGET(configuration.entrypoint + configuration.api + "/user/outboundstatus/").respond(200, {"meta":{"apiVersion":"0.1","code":200,"errors":null},"response":{"allowed":false}});
      scope = $rootScope.$new();
      ctrl = $controller('SendServiceCtrl', {$scope: scope});
  }));

  it('Should get the status', function() {

    scope.serviceId = '09bb5943fa2881e1';
    scope.getStatus();
    $httpBackend.whenGET(configuration.entrypoint + configuration.api + '/outbound/service/' + scope.serviceId).respond(200, {"meta":{"apiVersion":"0.1","code":200,"errors":null}});

  });

});

在单元测试中,我还在同一个控制器上进行了其他 $httpBackend 测试,但它们都运行得非常顺利。我做错了什么?

【问题讨论】:

    标签: angularjs jasmine karma-runner httpbackend


    【解决方案1】:

    您需要在调用该方法之前提供whenGET。

    it('Should get the status', function() {
        scope.serviceId = '09bb5943fa2881e1';
        $httpBackend.whenGET(configuration.entrypoint + configuration.api + '/outbound/service/' + scope.serviceId).respond(200, {"meta":{"apiVersion":"0.1","code":200,"errors":null}});
        scope.getStatus();
    });
    

    设置请求的期望,然后触发请求。

    希望这会有所帮助。

    【讨论】:

    • 模板也会导致此故障。
    • 你认为像ui.bootstrap 这样使用$templateCache 会消除模拟GET 的需要吗?
    • @domokun 你能发布一个链接到使用它的地方吗?
    • @domokun 如果你仔细观察,他们使用内联 HTML 元素,而不是从真实文件中加载模板。
    • @P.M "jsified" 模板,准确地说是 grunt-html2js 插件
    猜你喜欢
    • 2016-01-17
    • 2015-08-27
    • 2015-05-28
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    相关资源
    最近更新 更多