I am trying to test the reciever from a $broadcast (from a controller) in my directive via .on.
Directive:
describe('<-- myDirective Spec ------>', function () {
var scope, $compile, element, $httpBackend, rootScope;
beforeEach(angular.mock.module('myApp'));
beforeEach(inject(function (_$rootScope_, _$compile_, _$httpBackend_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
$httpBackend = _$httpBackend_;
rootScope = _$rootScope_;
var html = '<my-directive></my-directive>';
element = $compile(angular.element(html))(scope);
spyOn(scope, '$broadcast').and.callThrough();
scope.$digest();
}));
it('should be defined', function () {
expect(element).toBeDefined();
});
it('should broadcast ', function () {
scope.$broadcast('sendEmail');
expect(scope.$on).toHaveBeenCalledWith('sendEmail', jasmine.any(Function));
});
});
With the above, i get error:
Expected a spy, but got Function.
Update:
You can either test simply if your $broadcast is getting called with
expect(scope.$broadcast).toHaveBeenCalled()
or to actually test $on do something like
scope.$on('sendEmail', spyFunction)
expect(spyFunction).toHaveBeenCalledWith('sendEmail')
Reason: $broadcast doesn't actually calls $on function. $on is a listener which calls the callback function (passed as second argument) when it listens the event (first argument).
You are currently spying on $broadcast function of the scope, and have put a test on $on function. You need to replace
spyOn(scope, '$broadcast').and.callThrough();
by
spyOn(scope, '$on').and.callThrough();