21

从这里关注 AngularJS 文档

问题是文档只描述了代码的“成功/快乐”分支,并没有关于如何测试“失败”分支的示例。

我要做的是设置触发$scope.status = 'ERROR!'代码的前提条件。

这是一个最小的例子。

// controller
function MyController($scope, $http) {

  this.saveMessage = function(message) {
    $scope.status = 'Saving...';
    $http.post('/add-msg.py', message).success(function(response) {
      $scope.status = '';
    }).error(function() {
      $scope.status = 'ERROR!';
    });
  };
}

// testing controller
var $httpBackend;

beforeEach(inject(function($injector) {
  $httpBackend = $injector.get('$httpBackend');
}));

it('should send msg to server', function() {

  $httpBackend.expectPOST('/add-msg.py', 'message content').respond(500, '');

  var controller = scope.$new(MyController);
  $httpBackend.flush();
  controller.saveMessage('message content');
  $httpBackend.flush();

  // Here is the question: How to set $httpBackend.expectPOST to trigger
  // this condition.
  expect(scope.status).toBe('ERROR!');
});

});
4

1 回答 1

13

controller您在设置范围的属性时正在检查 的属性。

如果你想controller.status在你的expect通话中进行测试,你应该this.status在你的控制器中设置而不是$scope.status.

另一方面,如果你$scope.status在你的控制器中设置,那么你应该在你的调用中使用scope.status而不是。controller.statusexpect


更新:我在 Plunker 上为您创建了一个工作版本:

http://plnkr.co/edit/aaQ7JQV9WlXhou0PYHTn?p=preview

现在所有的测试都通过了...

于 2013-06-16T12:21:35.930 回答