I have created a few controllers using the .$on method and have successfully tested them. You can view an example on Plunker: http://plnkr.co/edit/8cwcdPc26PVAURmVFR8t?p=preview
Currently, I am working on a directive that also uses the .$on method in its link function:
app.directive('myDirective', function($rootScope, $timeout) {
return {
restrict: 'A',
replace: true,
scope: {},
link: function(scope,element,attrs){
scope.$on("step1", function(event) {
$rootScope.$broadcast('step3');
scope.hidden = false;
scope.shown = false;
});
scope.$on("step2", function(event) {
scope.msg = '';
scope.errorCase = false;
scope.infoCase = false;
});
scope.$on("step3", function(event) {
scope.hidden = true;
});
},
template:
'<div class="wrapper">' +
'<p>{{ msg }}</p>' +
'</div>'
};
});
I have written the following test for this directive:
describe('myDirective', function () {
var $scope, compile, element;
beforeEach(module('myApp'));
beforeEach(inject(function ($rootScope, $compile) {
$scope = $rootScope.$new();
element = angular.element("<section my-directive></section>");
$compile(element)($scope);
$scope.$digest();
}));
it('should initialise step1', function (){
var sub_scope = $scope.$new();
sub_scope.$emit('step1');
expect($scope.hidden).toBeFalsy();
expect($scope.shown).toBeFalsy();
});
});
However, the test is not running at all and no errors are being displayed. It seems like the approach I took for testing the controller is not correct for the directive. Any suggestions?