尝试在茉莉花下面测试这个函数,它基本上会退出给定的函数n次。
this.retry = function (fn, n){
return $q.when().then(function r(){
return fn().catch(function(err){
return (n-- <= 0) ? $q.reject(err) : r();
});
});
}
这是我的测试代码,
describe('persistenceService:retry Method', function () {
var $q;
var simulate;
var qFn;
var $rootScope;
var $timeout;
beforeEach(inject(function (_$q_, _persistenceService_, _$rootScope_, _$timeout_) {
persistenceService = _persistenceService_;
$q = _$q_;
$rootScope = _$rootScope_;
$timeout = _$timeout_;
simulate = function simulate(){
return $timeout(function(){
if(i < 4){
i++;
return $q.reject("Err");
}
console.log("Done");
}, 500);
};
qFn = spyOn($q, 'when').andCallThrough();
}));
afterEach(function() {
$rootScope.$apply();
});
it('should call $q.when()', function () {
persistenceService.retry(simulate, 5);
expect(qFn).toHaveBeenCalled();
});
it('should call $q.when()', function () {
expect(persistenceService.retry(simulate, 5)).toBe(' ');
});
});
第一次测试通过,因此$ q被调用。然而第二个给我一个如下所示的输出,
Expected { $$state : { status : 0 } } to be ' '.
答案 0 :(得分:0)
您应该尝试测试行为而不是界面。以下是您希望帮助的服务+测试的简化版本:
功能性:我有一些函数,重试,它接受一个返回一个promise的函数,当被拒绝时递减一个也传入的值,并用拒绝的错误数据做某事???
所以在代码中
this.retry = function (fn, n){
return fn().catch(function(errorData){
n = n - 1;
console.log(errorData);
return n;
});
}
describe('persistenceService:retry Method', function () {
var $q;
var simulateDeferred;
var simulate;
var $rootScope;
var $timeout;
beforeEach(inject(function (_$q_, _persistenceService_, _$rootScope_, _$timeout_) {
persistenceService = _persistenceService_;
$q = _$q_;
$rootScope = _$rootScope_;
simulateDeferred = $q.defer();
simulate = jasmine.createSpy().and.returnValue(simulateDeferred);
}));
it('should return a promise that calls the given function', function () {
var count = 5;
persistenceService.retry(simulate, count);
expect(simulate).toHaveBeenCalled();
var decrementedCount;
simulateDeferred.reject({'error': 'some message'}).then(function(rejectResult) {
decrementedCount = rejectResult
});
$rootScope.$digest(); // must be done for promise to reject / resolve
expect(decrementedCount).toEqual(count - 1);
});
});