angularjs unit test when to use $rootScope.$new()

ぃ、小莉子 提交于 2019-12-11 03:52:37

问题


I don't really understand when I should use the $rootScope = $rootScope.$new() in my angular unit tests. This snipped you see in many unit test examples. But in the following example that doesn't work:

angular.module("app.root", []).factory("rootFct", function ($rootScope) {
    $rootScope.amount = 12;
    return {
        getAmount: function () {
           return ($rootScope.amount + 1);
        }
    }
});

The associated unit Test doesn't work:

describe('Amount Tests', function() {
    var rootFct, $rootScope;

    beforeEach(function() {
        angular.mock.module("app.root");
        angular.mock.inject(function (_rootFct_, _$rootScope_) {
            $rootScope = _$rootScope_.$new();
            rootFct = _rootFct_;
        });
    });

    it('Set Amount in rootScope on 10', function() {
        var result = rootFct.getAmount();
        expect(result).toBe(13);
        $rootScope.amount = 15;
        result = rootFct.getAmount();
        expect(result).toBe(16);
    });
});

it only works when I am changing the

$rootScope = _$rootScope_.$new();

to

$rootScope = _$rootScope_;

and so I don't really understand when to use the $new() and for what its good for?


回答1:


$new() is mainly used when creating a new scope out of an existing scope.

Your code is already injecting rootScope in the service so it would not hold any difference.

$new() can be used when you want to get some attributes from the parent scope with/without isolation.

It takes two params isolate and parent. Isolate (boolean) need to be used if isolation from parent scope is required. Parent (object) Explicitly defining the parent scope.

Do note that a new scope created manually needs to be destroyed manually as well.

More on it over here




回答2:


As we know $rootScope is a global scope in out Angular app, and it holds true for unit test too. Angular framework will create a $rootScope object while unit testing too.

Since you are injecting your service into the test, Angular DI uses the global $rootScope and automatically injects it into the service.

You doing $rootScope = _$rootScope_.$new(); will not make any different. Here you are not injecting the dependency into the service, as is the case with controller, where we create scope with $new and inject it using the $controller You need to have the original $rootScope to assert your service behavior.



来源:https://stackoverflow.com/questions/28536866/angularjs-unit-test-when-to-use-rootscope-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!