The reason for this behavior lies in the way you are attaching the callback function. Modify
service.$on('hello', service.method);
to
service.$on('hello', function() {
service.method();
});
When using spyOn(service, 'method')
, you are essentially instructing to replace the current value referenced at service.method
with a spy function. However, in your original code snippet, the service.$on
method does not access the value of service.method
when the event is triggered. Instead, it retrieves the value during the initialization of the service. Therefore, changing the reference that service.method
points to at a later point will have no impact.