我正在尝试对失败的http请求进行单元测试。我有类似
的东西JS控制器
myFactory.getName(url)
.then(function(returnData) {
console.log(returnData) //works
}, function() { //not cover
console.log('error') //never get called //not cover
$timeout(function() { //not cover
//do stuff //not cover
}, 100); //not cover
});
我的工厂
factory.getName = function(url) {
return $http.get(url);
};
单元测试
beforeEach(module('muApp'));
beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_, _$timeout_, myFactory_) {
scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
$timeout = _$timeout_;
$rootScope = _$rootScope_;
myFactory = _$myFactory_;
myCtrl = _$controller_('myCtrl', {
'$scope': scope
});
$httpBackend.expectGET('/api/request/aaa').respond(404);
}));
describe('test' , function(){
it('should show error if request fail', function() {
myFactory.getName('/api/request/aaa');
$httpBackend.flush();
});
//Will show error but still won't cover the call back function
it('should show error if request fail', function() {
myFactory.getName('/api/request/aaa').then(function() {
}, function(){
console.log('error') // this will show in my karma
});
$httpBackend.flush();
});
})
我想介绍一下回调错误功能,但不知道这里有什么问题。谢谢你的帮助!