I am currently testing a custom directive which uses promises.
The structure of the first part of code segment of the directive is as follows:
angular.module('app').directive('simpleMock', [
'$q',
function ($q) {
'use strict';
return {
link: function ($scope) {
$scope.$watch('acc.mockPromise', function (promise) {
var sF;
$scope.sF = sF = {};
promise.then(function (res) {
sF.res = res;
return $q.when(res.fetchData());
}).then(function (data) {
sF.data = data;
return $q.when(sF.res.fetchLinks('create'));
}).then(function (links) {
if (!links.length) {
return $q.when(sF.res.fetchLinks('edit'));
}
return links;
})....
...............
The jasmine test spec that I wrote has the following structure:
beforeEach(module('app'));
beforeEach(inject(function ($rootScope, $compile) {
when = modulejs.require('when');
sF = {};
res = jasmine.createSpyObj('res', ['fetchData', 'fetchLinks']);
sF.res = res;
res.fetchData.andReturn(when([{
href: 'http://promise.angularjs.com/',
name: 'undefined',
rel: 'rel',
title: "Fake link"
}]));
res.fetchLinks.andReturn(when([{
href: 'http://promise.angularjs.com/',
name: 'undefined',
rel: 'rel',
title: "Fake link"
}]));
compile = function (acc, res) {
var $childScope, $parentScope, element;
element = angular.element('<div simple-mock></div>');
$parentScope = $rootScope.$new();
$parentScope.acc = acc;
acc.mockPromise = res;
$childScope = $parentScope.$new();
$compile(element)($childScope);
$parentScope.$digest();
return $childScope;
};
getRootScope = function () {
return $rootScope;
}
}));
it('calls fetchData', function () {
var $scope, acc, $rootScope;
acc = {};
$scope = compile(acc, when(res));
$rootScope = getRootScope();
$scope.$apply();
$rootScope.$apply();
$rootScope.$apply();
$rootScope.$apply();
$scope.acc.mockPromise.then(function () {
expect($scope.sF.res.fetchData).toHaveBeenCalled();
});
While running this test, control is not getting into this section of the directive code.
.then(function (data) {
sF.data = data;
return $q.when(sF.res.fetchLinks('create'));
[However, the control gets in till the previous line of code.]
A probable reason for this issue could be that the promises are not getting resolved. Also, no error or exception is thrown. Any suggestions in resolving the 'when' promise in the spec - so that the control gets into the following section of the directive:
}).then(function (data) {
sF.data = data;
return $q.when(sF.res.fetchLinks('create'));
}).then(function (links) {
if (!links.length) {
return $q.when(sF.res.fetchLinks('edit'));
}
return links;
})