Reputation: 3458
I am a little confused on testing $emit inside of a controller. The controller I am setting up exists inside of a directive. I am confused about two parts on setting up the test. How to set up $emit in the test? I am using Jasmine so I did a
spyON(scope, '$emit')
My test could not find an object to spy on. Here is my test.
describe('hero Directive', function () {
var $compile,
$rootScope,
scope,
element,
ctrl;
beforeEach(function () {
angular.mock.module('ha.module.core');
I am defining the controller and setting a scope inside the inject. I compiled the html so that I could use the directive.
angular.mock.inject(function (_$compile_, _$rootScope_, _$controller_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
scope = $rootScope.$new();
I assumed the error could be in the controller but it seems to be set up correct.
ctrl = _$controller_('ExploreHeroController', { scope: scope });
the directive uses templateUrl I am hoping that I can test with mock out a div and compile it.
var html = '<div explore-hero></div>';
element = $compile(angular.element(html))(scope);
scope.$digest();
});
});
describe('directive controller', function () {
it('should dispatch call $emit with $methodsBound', function () {
spyOn(scope, '$emit');
//expect(scope.$emit).toHaveBeenCalledWith('$methodsBound');
});
});
});
the emit sits inside of my directives controller
var controller = function($scope) {
$scope.$emit('$methodsBound');
}
Upvotes: 0
Views: 189
Reputation: 11
Your directive creates an isolated scope, which is calling $emit,so you need to define this one:
var elementScope;
//beforeEach
el = angular.element('<your-directive></your-directive>');
$compile(el)(scope);
scope.$digest();
elementScope = el.isolateScope();
it('should spy isolated scope', function(){
spyOn(elementScope, '$emit');
expect(elementScope.$emit).toHaveBeenCalledWith('$methodsBound');
})
Upvotes: 1