How Do I Inject $rootScope Into An AngularJS Unit Test?
Suppose I have a service that depends on a value in $rootScope, as with the following (trivial) service: angular.module('myServices', []) .factory('rootValGetterService', function(
Solution 1:
...
var $rootScope;
beforeEach(inject(function(_$rootScope_) {
$rootScope = _$rootScope_;
}));
...
Solution 2:
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);
}
}
Solution 3:
Include angular-mocks.js
, then use angular.mock.inject
:
Solution 4:
Instead of creating a new scope as you would if you were injecting $scope
you can mock the properties you need directly into $rootScope
.
Then $rootScope
will be injected with those properties available in the code you are testing.
At least this is the way I solved the same problem.
The following code should work in your example.
beforeEach(inject(function($rootScope) {
$rootScope.specialValue = 'whatever';
}));
Solution 5:
Just try to give a more detailed answer including the test case:
...
var $rootScope;
beforeEach(inject(function(_$rootScope_) {
$rootScope = _$rootScope_;
}));
...
it('getVal returns the value from $rootScope', function() {
var value = 12345;
$rootScope.specialValue = value;
expect(testRootValGetterService.getVal()).toBe(value);
}
Post a Comment for "How Do I Inject $rootScope Into An AngularJS Unit Test?"