AngularJs单元测试隔离范围指令

时间:2015-02-18 11:30:04

标签: angularjs unit-testing angularjs-scope jasmine

我想测试以下指令“spinInput”,它需要ngModel,但是我无法访问指令的范围。我得到的只是一个空洞的范围。使用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();
    });


});

2 个答案:

答案 0 :(得分:5)

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

我已经能够成功地测试隔离范围,如下所示。

您可以查看在此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'); 
});

});

答案 1 :(得分:2)

尝试在element.isolateScope()

之前放置outerScope。$ digest()