0

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.
Oam Psy
  • 8,555
  • 32
  • 93
  • 157

1 Answers1

1

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();
yoogeeks
  • 965
  • 8
  • 24
  • tired this, see error: Expected spy $on to have been called with [ 'sendEmail', ] but it was never called. – Oam Psy Mar 04 '16 at 09:23
  • 1
    That's a different problem. It means your test is failing, i.e. $on is not getting called, reason : It never actually gets called, it's the callback function you pass as the second argument that get's called, with the first argument as parameter. – yoogeeks Mar 04 '16 at 09:40