2016-10-30 40 views
2

噶不斷拋出TypeError: Cannot read property 'originalPath' of undefined給出的link功能如下所示的指令:如何在指令鏈接函數中單元測試Angular 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{}}。我試過將模擬路線傳遞給廣播消息,但沒有任何改變。我將如何獲得預期的(默認)路徑傳入指令?這是否正確的方式去跟蹤鏈接中的路線變化?我的猜測是我只是茉莉花和單元測試的新手。

回答

0

我終於想通了如何觸發使用$route.reload()

路線改變從docs,它:

導致$航線的重新加載,即使$位置並沒有改變目前的路線。因此,ngView創建新的範圍並重新實例化控制器。

於是補充說我的測試「重新啓動」路線,迫使routeChangeSuccess發出,一旦消化,通入link。下面是從spec文件更新的塊,並添加了$位置更改以測試其他路由:

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'); 
    }); 
}); 
相關問題