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

时间:2013-03-14 17:21:19

标签: javascript unit-testing dependency-injection angularjs jasmine

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

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

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

7 个答案:

答案 0 :(得分:21)

...
var $rootScope;
beforeEach(inject(function(_$rootScope_) {
  $rootScope = _$rootScope_;
}));
...

答案 1 :(得分: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);
    }
}

答案 2 :(得分:3)

包括angular-mocks.js,然后使用angular.mock.inject

答案 3 :(得分:0)

试着提供一个更详细的答案,包括测试用例:

...

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);
    }

答案 4 :(得分:0)

这就是我的所作所为:

it('some kind of wacky test', function($rootScope, Translate){
    $rootScope.lang = 'en';
    expect(Translate('overview').toBe('Overview');
}

答案 5 :(得分:0)

希望这有助于其他人,因为这是解决类似问题的方法。

var rootValGetterService;

beforeEach(inject(function($rootScope,$injector) {
    $rootScope.specialValue = "test";
    rootValGetterService= $injector.get('rootValGetterService');
}));

it("Should have a service", function () {
    expect(rootValGetterService).toBeDefined();
});

答案 6 :(得分:0)

您可以直接在$scope中模拟所需的属性,而不是像注入$rootScope那样创建新范围。

然后$rootScope将注入您正在测试的代码中可用的属性。

至少这是解决同样问题的方法。

以下代码应该适用于您的示例。

beforeEach(inject(function($rootScope) {
    $rootScope.specialValue = 'whatever';
}));