测试指令控制器AngularJS Karma

时间:2014-04-23 08:20:00

标签: angularjs unit-testing angularjs-directive karma-runner karma-jasmine

我无法访问控制器值,一切都未定义。我可以在日志中看到值,但无法访问它们。是否有一种创建指令和测试其控制器的首选方法。我不想用.controller(' Ctrl')创建一个控制器,因为它是整个应用程序的全局控制器,它可以被覆盖。

'use strict';

angular.module('Widgets.Module')
.directive('ntGrid', [
    'Generator',
    function (Generator) {
        function postLink(scope, jqElm, attr) { }

        function postCompile(tElement, tAttrs) {
            return function postLink2(scope, jqElm, attr) {
                attr.$observe("ntId", function (id) { // called on on init
                    scope.ntId = id !== 'generate' ? id : Generator.id;
                });
            }
        }

        function CtrlGrid(scope, attrs, Generator) {
            var ctrl = scope;

            ctrl.dataStatus = 'No Data';
            ctrl.isLoading = '';
        }

        return {
            template:
                '<div id="{{ ntId }}">' +
                '</div>',
            controller: [
                '$scope', '$attrs', CtrlGrid
            ],
            replace: true,
            scope: {
                ntId: '@'
            },
            restrict: 'EA',
            link: postLink,
            compile: postCompile
        };

    }
])
;

这是我的考验。

describe('testing ntGrid', function () {
    beforeEach(inject(function ($compile, $rootScope) {
        $scope = $rootScope.$new();
        $scope.data = [
            [
                {class: 'description', value: 'Header1'},
                {class: 'description', value: 'Header2'}
            ],
            [
                [
                    {class: 'value', value: '13'},
                    {class: 'smallvalue', value: '6,43%'}
                ],
                {class: 'value', value: '12'},
                {class: 'smallvalue', value: '4,23%'}
            ],
            [
                [
                    {class: 'negativevalue', value: '-13'},
                    {class: 'negativevalue smallvalue', value: '-6,43%'}
                ],
                {class: 'negativevalue', value: '12'},
                {class: 'negativevalue smallvalue', value: '4,23%'}
            ]
        ];
        element = angular.element('<div nt-grid nt-table="data"></div>');
        $compile(element)($scope);
        $scope.$digest();
        ctrl = element.data('$scope');
    }));

    it('test ntGrid html', inject(function () {

        console.log(ctrl.ntId)
        console.log($scope.ntId)
    }));

});

1 个答案:

答案 0 :(得分:0)

这就是我如何获得指令控制器的范围。

var _scope = element.isolateScope();