Unit testing 如何使用mock$httpBackend测试错误分支
我正在跟踪 问题在于,文档只描述了代码的“成功/快乐”分支,没有关于如何测试“失败”分支的示例 我想做的是设置触发Unit testing 如何使用mock$httpBackend测试错误分支,unit-testing,testing,angularjs,Unit Testing,Testing,Angularjs,我正在跟踪 问题在于,文档只描述了代码的“成功/快乐”分支,没有关于如何测试“失败”分支的示例 我想做的是设置触发$scope.status='ERROR!'的前提条件代码 这里是一个最小的例子 // controller function MyController($scope, $http) { this.saveMessage = function(message) { $scope.status = 'Saving...'; $http.post('/add-msg
$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
,则应在expect
调用中使用scope.status
而不是controller.status
更新:我在Plunker上为您创建了一个工作版本:
现在所有的考试都通过了…谢谢你的回答。我已经更新了示例。。。这只是官方文件的复制粘贴。这并不能回答我的问题。模拟仍然会调用success
分支。我在Plunker上创建了一个工作版本,并在我的主要答案中添加了链接。谢谢。你是个英雄!:)不客气,很高兴我能帮上忙。祝你的项目好运!