AngularJs 单元测试隔离范围指令

AngularJs Unit Testing isolated scope Directive

我想测试以下需要 ngModel 的指令 "spinInput",但我无法访问该指令的范围。我得到的只是一个空范围。 Angularjs 使用 1.3.13。

指令:

angular.module('charts.spinInput',[]).directive('spinInput', function() {
return {
    restrict: 'E',
    replace: true,
    require:'ngModel',
    scope: {
      min:"@"
    },
    controller:function($scope)
    {
        $scope.test=12;

      $scope.calcAngle=function(point)
        {
            var xDif=point.x-50;
            var yDif=point.y-50;

            return (Math.atan2(yDif, xDif) * 180 / Math.PI);

        };

},

    templateUrl: 'charts/directive/spinInput/spinInput.html',
    link:function(scope, element, attr,ngModel) {
       ...
    }

    };
});

单元测试: 抛出以下错误:TypeError:'undefined' 不是对象(评估 'innerScope.min')

 describe('spinInput', function() {

 beforeEach(module('charts'));

    var $httpBackend;
    var element;
    var outerScope;
    var innerScope;




    beforeEach(inject(function($rootScope, $compile  , $injector) {
        element = angular.element('<spin-input min="12"></spin-input>');
        $httpBackend = $injector.get('$httpBackend');
        $httpBackend.whenGET('charts/directive/spinInput/spinInput.html').respond(200, '');
        outerScope = $rootScope.$new();
        $compile(element)(outerScope);

        innerScope = element.isolateScope();

        outerScope.$digest();
    }));


    it('scope.min should be defined', function() {
        expect(innerScope.min).toBeDefined();
    });


});

尝试将 outerScope.$digest() 放在 element.isolateScope()

之前

您构建测试的方式似乎导致了问题。

我已经能够按照以下方式成功测试隔离范围。

您可以在此 jsfiddle 上查看测试 运行(模板代码已注释掉)。

describe('Directive: spinInput', function() {

var scope, compile, validHTML, templateHtml;;


validHTML = '<spin-input min="12"></spin-input>';

beforeEach(module('myApp'));

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

    templateHtml = $templateCache.get('charts/directive/spinInput/spinInput.html');
    if(!templateHtml) {
            templateHtml = $.ajax('charts/directive/spinInput/spinInput.html', {async: false}).responseText;
            $templateCache.put('charts/directive/spinInput/spinInput.html', templateHtml)
    }


    scope = $rootScope.$new();
    compile = $compile;
}));

function create() {
    var elem, compiledElem;
    elem = angular.element(validHTML);
    compiledElem = compile(elem)(scope);
    scope.$digest();

    return compiledElem;    
}


it('scope.min should be defined', function() {
    var el = create();
    expect(el.isolateScope().min).toBeDefined();
});

it('scope.min should equal 12', function() {    
    var el = create();
    expect(el.isolateScope().min).toEqual('12'); 
});

});