Reputation: 16618
How do I do a jasmine unit test for my angular directive that needs to test its emit?
This directive is a attribute directive and has an emit inside the directive that I need to test.
hows best to do this?
This is my current test:
//broadcast test:
describe('broadcast called', function() {
var rootScope, testService;
beforeEach(inject(function(_$rootScope_, $injector) {
rootScope = _$rootScope_;
testService = $injector.get('testFactory');
spyOn(rootScope, "broadcast");
}));
it('should be broadcast', function() {
testService.emitTest();
expect(rootScope.broadcast).toHaveBeenCalledWith('test1');
});
});
Current code:
appservicemod.factory('testFactory', ['$rootScope', function ($rootScope) {
var emitTest = function(){
$rootScope.$broadcast('test1');
}
return {
emitTest: emitTest
}
}
]);
Upvotes: 0
Views: 76
Reputation: 12701
It seems your current approach works fine, except for a few issues:
$broadcast
, not broadcast
everywherebeforeEach(module('app'))
in your codeIf you fix these issues, it works: http://jsfiddle.net/MMiszy/c4fz58sp/1/
describe('broadcast called', function() {
var $rootScope, testService;
beforeEach(module('app'));
beforeEach(inject(function(_$rootScope_, $injector) {
$rootScope = _$rootScope_;
spyOn($rootScope, "$broadcast");
testService = $injector.get('testFactory');
}));
it('should broadcast', function() {
testService.emitTest();
expect($rootScope.$broadcast).toHaveBeenCalledWith('test1');
});
});
Upvotes: 1
Reputation: 1291
spy
spyOn(scope, 'emit');
and in the test verify it was called
expect(scope.emit).toHaveBeenCalledWith('valueItShouldBeCalledWith');
Upvotes: 1