I am trying to test the next angular directive. It listens to ui-route $stateChange event to show a progress indicator.
angular.module('sm.components.progress', ['ui.router'])
.directive('smProgress', function($rootScope) {
return {
restrict: 'E',
replace: true,
template: '<div class="in-progress" ng-if="isRouteLoading">' +
'<span>.</span><span>.</span><span>.</span>' +
'<div/>',
controller: function($scope) {
$scope.isRouteLoading = false;
$rootScope.$on('$stateChangeStart',
function() {
$scope.isRouteLoading = true;
});
$rootScope.$on('$stateChangeSuccess',
function() {
$scope.isRouteLoading = false;
});
}
};
});
This is my test code:
describe('smProgress', function() {
var $compile, $rootScope, element, scope;
beforeEach(module('sm.components.progress'));
beforeEach(inject(function(_$compile_, _$rootScope_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
scope = $rootScope.$new();
}));
afterEach(function() {
element.remove();
});
it('$rootScope.isRouteLoading should be false on start',
function() {
element = $compile('<sm-progress></sm-progress>')(scope);
scope.$digest();
expect(scope.isRouteLoading).toBe(false);
$rootScope.$emit('$stateChangeStart');
//The directive listen to the $stateChangeStart and
//scope.isRouteLoading become true as expected
expect(scope.isRouteLoading).toBe(true);
scope.$digest();
// checks if the template is rendered when ng-if evaluates true
// how?
}));
});
The ng-if in the template start evaluating to false, so the element is removed from the DOM. When I emit manually the $stateChangeStart event, the directive listener works, but I can't find the element in the DOM.
How can I check if the template is added to then DOM when the ng-if evaluates to true again?