如何在Jasmine Test中访问指令的范围

时间:2015-08-10 13:51:56

标签: javascript angularjs angularjs-directive jasmine karma-jasmine

我无法获得我的指令范围(另一个选择是我得到了范围,但我的功能不存在)。我使用Jasmine而不是Karma。

我的指示:

angular.module('taskApp').directive('nkAlertDir', ['$http', function ($http) {
    return {
        template: "<span>{{msg}}</span>",
        replace: true,
        link: function (scope, elem, attrs) {
            scope.values = {
                canvas: canvasSize,
                radius: size,
                center: canvasSize / 2
            };

            $http.get('someUrl')
                .suncces(function (data) {
                    scope.msg = data;
                })
                .error(function (err) {
                    //there is always be error because this url does nor exist
                    //but this is not the point in this exercise
                });

            scope.returnNumbers = function () {
                return [2, 2];
            }
        }
    }
}]);

我的测试:

describe('Unit: Directives', function () {

    var element;
    var scope;

    beforeEach(module('taskApp'));

    beforeEach(inject(function ($compile, $rootScope) {

        scope = $rootScope;
        element = angular.element('<div nk-alert-dir></div>');

        scope.size = 100;
        $compile(element)(scope);
        scope.$digest();
    }));

    it('should bind an alert message of "task added!"', function () {

        var dirScope = element.isolateScope();
        console.log(dirScope);
    });
});

不知怎的,我总是得到dirScope未定义 我试过这个:

  • 替换了digest()
  • 中的$apply()
  • 替换了$rootScope
  • 中的$rootScope.$new()

1 个答案:

答案 0 :(得分:2)

您的指令中没有隔离范围,因此element.isolateScope()将返回undefined。

尝试访问范围:element.scope()

如果要在指令上使用隔离范围,则必须将指令定义对象的scope属性设置为JS对象并在其中添加属性。然后,您就可以使用element.isolateScope来访问隔离范围。

return {
        template: "<span>{{msg}}</span>",
        replace: true,
        scope : {},   // Any properties you want to pass in to the directive on scope would get defined here
        link: function (scope, elem, attrs) {
            scope.values = {
                canvas: canvasSize,
                radius: size,
                center: canvasSize / 2
            };

            $http.get('someUrl')
                .suncces(function (data) {
                    scope.msg = data;
                })
                .error(function (err) {
                    //there is always be error because this url does nor exist
                    //but this is not the point in this exercise
                });

            scope.returnNumbers = function () {
                return [2, 2];
            }
        }
    }