I wrote a Jasmine test to see whether the finally()
block is called on each function execution no matter what the chained promises returned.
describe('myController Test Suite', function(){
var q, scope, deferred, myService;
// Initialize the Pointivo module
beforeEach(function(){
module('myApp');
});
// Mock out fake service
beforeEach(function(){
myService = {
myFirstPromise: function(){
deferred = q.defer();
// TEST ME
deferred.resolve('first promise response');
return deferred.promise;
},
mySecondPromise: function(){
deferred = q.defer();
// TEST ME
deferred.resolve('second promise response');
return deferred.promise;
},
myThirdPromise: function(){
deferred = q.defer();
// TEST ME
deferred.resolve('third promise response');
return deferred.promise;
}
};
spyOn(myService, 'myFirstPromise').and.callThrough();
spyOn(myService, 'mySecondPromise').and.callThrough();
spyOn(myService, 'myThirdPromise').and.callThrough();
});
// Assign controller scope and service references
beforeEach(inject(function($controller, $rootScope, $q){
scope = $rootScope.$new();
q = $q;
$controller('myController', {
$scope: scope,
myService: myService
});
}));
describe('finally test', function(){
it('should always hit the finally statement', function(){
scope.finallyStatementFlag = false;
scope.test();
scope.$apply();
expect(scope.finallyStatementFlag).toBeTruthy();
});
});
});
The above rests on the assumption that the controller looks like:
myApp.controller('myController', function($scope, myService){
$scope.finallyStatementFlag = false;
$scope.test = function(){
myService.myFirstPromise()
.then(function(data){
console.log(data);
return myService.mySecondPromise()
})
.then(function(data){
console.log(data);
return myService.myThirdPromise();
})
.then(function(data){
console.log(data);
})
.finally(function(){
console.log('finally statement');
$scope.finallyStatementFlag = true;
});
}
});
The above will pass even if you change any or all of the deferred.resolve()
to deferred.reject()
inside of the beforeEach()
callback where we define myService
.
Fiddle example