SpyOn $ scope. $ on after $ broadcast toHaveBeenCalled doesn't work
I'm having a lot of problems getting this simple test to work.
I have a listener $scope.$on
in my controller that I want to test. I just want to make sure he called after the broadcast.
To do this, I thought the following code would work:
describe("Testing the parent controller: ", function() {
var scope, ctrl;
beforeEach(function() {
module("myApp");
inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('parent-ctrl', {
$scope: scope,
});
});
});
it ("should trigger broadcast when current page updates", function() {
spyOn(scope, "$on");
scope.$broadcast("myEvent", 999);
expect(scope.$on).toHaveBeenCalled();
});
});
It is not ( Expected spy $on to have been called.
). I dug through a lot of examples:
- How can I check if an event was broadcast in AngularJS? in-angularjs
- How to check $ scope. $ on in AngularJS
- How do I check for events in angular?
- unit test spy on $ emit
- How to unit test $ scope.broadcast, $ scope. $ when using Jasmine
- How to check $ scope. $ on in AngularJS
- How to check event broadcast in AngularJS
and learned a lot, but for some reason I just don't make critical communication.
I've noticed that the handler $on
is responding to a post-assertion, which is useless. I've tried scope.$apply()
it .andCallThrough()
in various configurations as well, but nothing works.
How it's done?
source to share
When the event is broadcast, it is the listener function that was registered with $on
that is being executed, not the function itself $on
.
Your current test will work for code like this, which you probably don't have:
$scope.$on('myEvent', function () {
$scope.$on('whatever', someFn);
});
What you should be testing is what your registered listener function does.
So, if you, for example, have:
$scope.$on('myEvent', function() {
myFactory.doSomething();
});
Check it like this:
spyOn(myFactory, "doSomething");
scope.$broadcast("myEvent");
expect(myFactory.doSomething).toHaveBeenCalled();
source to share