Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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($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?

like image 281
Gregory Avery-Weir Avatar asked Mar 14 '13 17:03

Gregory Avery-Weir


People also ask

What is $rootScope in AngularJS?

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.

How do I get rootScope in AngularJS?

If you want to access root scope out side of controller, use: var rs = angular. element($('body')). scope(); then use rs.

How many $rootScope in AngularJS application can have?

An app can have only one $rootScope which will be shared among all the components of an app.

When would you use a $rootScope?

$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.


2 Answers

...
var $rootScope;
beforeEach(inject(function(_$rootScope_) {
  $rootScope = _$rootScope_;
}));
...
like image 93
Markus Coetzee Avatar answered Oct 13 '22 22:10

Markus Coetzee


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);
    }
}
like image 39
Gregory Avery-Weir Avatar answered Oct 13 '22 22:10

Gregory Avery-Weir