Suppose I have a service that depends on a value in $rootScope, as with the following (trivial) service:
angular.module('myServices', [])
.factory('rootValGetterService', function($rootScope) {
return {
getVal: function () {
return $rootScope.specialValue;
}
};
});
If I want to unit test this by putting a value in $rootScope, what is the best way to go about it?
All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive. The rootScope is available in the entire application. If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current scope.
If you want to access root scope out side of controller, use: var rs = angular. element($('body')). scope(); then use rs.
An app can have only one $rootScope which will be shared among all the components of an app.
$rootScope exists, but it can be used for evilScopes in Angular form a hierarchy, prototypally inheriting from a root scope at the top of the tree. Usually this can be ignored, since most views have a controller, and therefore a scope, of their own.
...
var $rootScope;
beforeEach(inject(function(_$rootScope_) {
$rootScope = _$rootScope_;
}));
...
By using provide(), you can inject a new $rootScope:
describe('in rootValGetter', inject(function ($rootScope) {
var scope;
var testRootValGetter;
beforeEach(function () {
scope = $rootScope.$new();
module(function ($provide) {
$provide.value('$rootScope', scope);
});
inject(function ($injector) {
testRootValGetterService = $injector.get('rootValGetterService');
});
});
it('getVal returns the value from $rootScope', function() {
var value = 12345;
scope.specialValue = value;
expect(testRootValGetterService.getVal()).toBe(value);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With