2016-10-30 3 views
2

카르마는 TypeError: Cannot read property 'originalPath' of undefined이 (가) link 기능에 다음과 지시어를 사용해 던지는 유지 :유닛 테스트 방법 지시 링크 기능에서 각도 routeChangeSuccess?

angular.module('myApp').directive('sidebar', ['$route', function ($route) 
{ 
    return { 
    restrict: 'E', 
    templateUrl: 'views/sidebar.html', 
    scope: { 
     activeNav: '@' 
    }, 
    link: function (scope, element, attrs) { 
     scope.$on('$routeChangeSuccess', function (event, curr, prev) { 
     scope.activeNav = curr.$$route.originalPath || '/about'; 
     }); 
    } 
} 

및 단위 테스트 :

describe('sidebar directive', function() { 
    var $compile, 
    $rootScope, 
    scope, 
    element; 

    beforeEach(module('MyApp')); 
    beforeEach(module('my.templates')); // ng-html2js karma template loader 

    beforeEach(inject(function(_$compile_, _$rootScope_){ 
    $compile = _$compile_; 
    $rootScope = _$rootScope_; 
    scope = $rootScope.$new(); 
    })); 


    it('defaults to /about route', function() { 
    element = $compile("<sidebar></sidebar>")(scope); 
    var linkScope = element.children().scope(); 

    $rootScope.$broadcast('$routeChangeSuccess'); 
    $rootScope.$digest(); 
    expect(linkScope.activeNav).toBe('/about'); 
    }); 
}); 

링크 내에서 curr 경로를 기록

내가 Object{params: Object{}, pathParams: Object{}, locals: Object{}}를 얻을. 나는 모의 라우트를 브로드 캐스트 메시지에 전달하려고 시도했지만 아무 것도 변경되지 않았습니다. 지시문에 예상되는 (기본) 경로를 전달하려면 어떻게해야합니까? 링크 내에서 경로 변경을 추적하는 것이 올바른 방법일까요? 제 생각 엔 Jasmine과 유닛 테스팅을 처음 접했을 것입니다.

답변

0

나는 결국, docs에서 그것을 $route.reload()

를 사용하여 경로 변경을 트리거하는 방법을 알아 냈 :

는 $의 위치가 변경되지 않은 경우에도 현재의 경로를 다시로드 $ 노선 서비스를하도록합니다. 그 결과, ngView는 새로운 범위를 만들고 컨트롤러를 다시 시작합니다.

내 테스트에 추가하면 라우트가 재부팅되고 routeChangeSuccess가 방출되고 한 번 소화되면 link으로 전달됩니다. 다음은 사양 파일에서 $ 위치가 변경되어 다른 경로를 테스트하는 업데이트 된 블록입니다.

describe('sidebar directive', function() { 
    var $compile, 
    $rootScope, 
    $route, 
    $location, 
    scope, 
    element; 

    beforeEach(module('MyApp')); 
    beforeEach(module('my.templates')); // ng-html2js karma template loader 

    beforeEach(inject(function(_$compile_, _$rootScope_, _$route_, _$location_){ 
    $compile = _$compile_; 
    $rootScope = _$rootScope_; 
    $location = _$location_; 
    $route = _$route_; 
    scope = $rootScope.$new(); 
    element = $compile("<sidebar></sidebar>")(scope); 
    })); 


    it('defaults to /about route', function() { 
    $route.reload(); 
    $rootScope.$digest(); 
    var linkScope = element.children().scope(); // Get directive's isolated scope 
    expect(linkScope.activeNav).toBe('/about'); 
    }); 

    it('sets activeNave to correct route on change', function() { 
    $location.path('/foo'); 
    $route.reload(); 
    $rootScope.$digest(); 
    var linkScope = element.children().scope(); 
    expect(linkScope.activeNav).toBe('/foo'); 
    }); 
});