I have a service that has $rootScope as a dependency ($rootScope is used in this service to listen for a logout event, which triggers the service clear some cached promises):
angular.module('myApp')
.factory('myService', [
'$rootScope',
myService
]);
/**
* Factory function for this service.
*/
function myService($rootScope) {
var service = {};
var myCachedPromise = undefined;
var myOtherCachedPromise = undefined;
/**
* Watch for logout event. Expire cached promises when this happens.
*/
$rootScope.$on('NOT_AUTHORIZED', onPageExpire);
/**
* Handler for log out/page expire event.
*/
function onPageExpire() {
console.log('Expiring caches!');
annotationChart = undefined;
gotAnnnotationData = undefined;
}
service.getSomeData = function() {
myCachedPromise = myCachedPromise || $http.get('/api/whatever');
return myCachedPromise;
};
service.getSomeOtherData = function() {
myOtherCachedPromise = myOtherCachedPromise || $http.get('/api/whatever');
return myOtherCachedPromise;
};
return service;
}
In my Jasmine test, I want to broadcast the NOT_AUTHORIZED event to trigger this service to call the onPageExpire function:
var myService,
$rootScope;
beforeEach(module('myApp'));
beforeEach(inject(function(_$rootScope_, _myService_) {
myService = _myService_;
$rootScope = _$rootScope_;
}));
it('should expire cached promises on log out', function() {
$rootScope.$broadcast('NOT_AUTHORIZED');
$rootScope.$digest();
});
Through some poking and prodding, it seems to me that the $rootScope in my test and the $rootScope being injected into the instance of myService isn't actually the same object, so when I do the broadcast in my test, the event handler in the service is not fired.
How do I ensure the $rootScope in the instance of the service is the same one as I'm using in my test?
Aucun commentaire:
Enregistrer un commentaire