如何使用模拟$ httpBackend测试错误分支如何使用、分支、错误、测试

2023-09-14 00:21:39 作者:先生丶扮可爱不是你的专利

我下面从这里的 AngularJS文档

问题是,该文档描述只有成功/幸福的code的分支,不存在如何测试失败分支的例子。

我想要做的,就是设置precondition用于触发 $ scope.status =错误! code

下面是一个最小的例子。

  //控制器功能myController的($范围,$ HTTP){  this.saveMessage =功能(消息){    $ scope.status ='保存...;    $ http.post('/ add-msg.py,消息).success(功能(响应){      $ scope.status ='';    })错误(函数(){      $ scope.status ='错误';    });  };}//测试控制器变量$ httpBackend;beforeEach(注入(函数($喷油器){  $ httpBackend = $ injector.get('$ httpBackend');}));它('应该送味精到服务器',函数(){  $ httpBackend.expectPOST('/ add-msg.py,短信内容)响应(500,'')。  无功控制范围=美元的新(myController的)。  $ httpBackend.flush();  controller.saveMessage('邮件内容');  $ httpBackend.flush();  //这里的问题是:如何设置$ httpBackend.expectPOST触发  //这个条件。  期待(scope.status).toBe(错误!');});}); 

解决方案 HTTP 错误 500.100 内部服务器错误 ASP 错误

您正在检查控制器的特性当您设定的范围的属性。

如果你想在你的期望呼叫测试 controller.status ,你应该设置 this.status 控制器,而不是 $ scope.status 中。

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

更新:我创建了一个工作版本为大家讲解Plunker:

http://plnkr.co/edit/aaQ7JQV9WlXhou0PYHTn?p=$p$pview

所有的测试现在路过...

I am following the AngularJS documentation from here

The problem is that the documentation describes only the "success/happy" branch of the code, and there is no example of how to test the "failure" branch.

What I want to do, is to set the precondition for triggering the $scope.status = 'ERROR!' code.

Here is a minimal example.

// 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!');
});

});

解决方案

You are checking a property of the controller while you are setting a property of the scope.

If you want to test for controller.status in your expect call, you should set this.status inside your controller instead of $scope.status.

On the other hand, if you set $scope.status in your controller, then you should use scope.status instead of controller.status in your expect call.

UPDATE: I created a working version for you on Plunker:

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

All tests are passing now...