Recently I had to write a service that awaits some event, sent in rootScope. My goal was to make a kind of "watcher", which is created at the start of the application and do some work at the event.
First lets make angular module that creates a coffee class for our factory:
First lets make angular module that creates a coffee class for our factory:
As you can see we inject $rootScope in our DataLoggingWatcher class instance. This class will be created only once (when we require DataLoggingWatcher)
In constructor we save $rootScope for future use (adding To make it work - we require DataLoggingWatcher in our main controller:
And final part: how to test our watcher? Simple test looks like this:
We inject $rootScope in beforeEach to broadcast our event in test. After that we spy on function call and expect, that method logToConsole will be called on event.And one more: to successfully spy on logToConsole method of our class we need to modify constructor:
So we call our logToConsole inside anonymous function because in that case will be called logToConsole method of instance DataLoggingWatche, not form class itself (and we can spy on it). Thats it. Full Gist