如何将$ rootScope注入AngularJS单元测试?

Gre*_*eir 13 javascript unit-testing dependency-injection jasmine angularjs

假设我有一个服务依赖于$ rootScope中的值,就像下面的(普通)服务一样:

angular.module('myServices', [])
.factory('rootValGetterService', function($rootScope) {
    return {
        getVal: function () {
            return $rootScope.specialValue;
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

如果我想通过在$ rootScope中添加一个值进行单元测试,那么最好的方法是什么?

Mar*_*zee 21

...
var $rootScope;
beforeEach(inject(function(_$rootScope_) {
  $rootScope = _$rootScope_;
}));
...
Run Code Online (Sandbox Code Playgroud)


Gre*_*eir 6

通过使用provide(),您可以注入一个新的$ 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这种模式对我不起作用.Angular不断抛出这个错误:"错误:注入器已经创建,无法注册模块!" (12认同)
  • 要有一个干净的$ rootScope,你可以尝试从beforeEach注入它:`beforeEach(inject(function($ rootScope){` (2认同)