加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

单元测试 – 如何使用mock $httpBackend来测试错误分支

发布时间:2020-12-17 08:16:44 所属栏目:安全 来源:网络整理
导读:我跟着 AngularJS documentation from here 问题是文档仅描述代码的“成功/快乐”分支,并且没有如何测试“失败”分支的示例。 我想做的是设置触发$ scope.status =’ERROR
我跟着 AngularJS documentation from here

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

我想做的是设置触发$ 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!');
});

});
在设置范围的属性时,您将检查控制器的属性。

如果你想在你的expect函数中测试controller.status,你应该在你的控制器里面设置this.status,而不是$ scope.status。

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

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

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

所有测试现在都过去了

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读