$ httpBackend jsonp:没有待刷新的待处理请求

时间:2015-08-22 06:39:55

标签: javascript angularjs unit-testing jsonp httpbackend

点击按钮,我进行了一次jsonp调用。

    function clickHandler(e) {
            e.preventDefault();
            var url = "some.url.with?params";
            $http.jsonp(url).success(function () {$scope.success();})
                            .error(function () {$scope.failure();});
        }

测试:

$httpBackend.expectJSONP(this.url + '&' + $.param(this.params)).respond({status: 200});

$('button').click();

$rootScope.$digest(); // this was suggested in few answers, doesn't work for me though

$httpBackend.flush();

但是我一直得到没有待处理的冲突失败请求

我们需要做些什么不同的JSONP调用。在其他任何地方,这种格式都有效。

PS:是的,我打电话(许多问题,人们实际上是打电话或触发触发事件的动作)。至少,我看到代码命中了我在代码中提出请求的行。

2 个答案:

答案 0 :(得分:0)

这不起作用,因为它看起来不像你在测试中创建了button DOM元素。如果您只是调用$scope对象上的函数,那么您的生活将更加轻松,您可以在测试中轻松访问该函数,因为您已经创建了它。试试这个:

DEMO

<强>控制器

var app = angular.module('plunker',[]);

app.controller('MainCtrl', function($scope, $http) {

  $scope.success = function(){
    console.log('success');
  };

  $scope.failure = function(){
    console.log('failure');
  };

  $scope.clickHandler = function(e) {
      e.preventDefault();
      var url = "some.url.with?params";
      $http
        .jsonp(url)
        .success($scope.success)
        .error($scope.failure);
  }

});

<强>规范

describe('Testing a controller', function() {

  var $scope, ctrl, $httpBackend, mockEvent;

  beforeEach(module('plunker'));

  beforeEach(inject(function($rootScope, $controller, _$httpBackend_){

    $scope        = $rootScope.$new();
    $httpBackend  = _$httpBackend_;

    mockEvent = { preventDefault: function(){} };

    ctrl = $controller('MainCtrl', {
      $scope: $scope
    });

  })); 

  it('should trigger success callback', function() {

    spyOn($scope, 'success');

    $httpBackend.expectJSONP('some.url.with?params').respond({status: 200});

    $scope.clickHandler(mockEvent);

    $scope.$digest();

    $httpBackend.flush();

    expect($scope.success).toHaveBeenCalled();

  });

});

答案 1 :(得分:0)

我的测试受到我的套件中的早期测试的影响,因此早期测试中的几个值很少被提取,这与我声称的不同。因此请求不匹配。纠正了他们。现在工作。抱歉,麻烦。

相关问题