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{}}
。我試過將模擬路線傳遞給廣播消息,但沒有任何改變。我將如何獲得預期的(默認)路徑傳入指令?這是否正確的方式去跟蹤鏈接中的路線變化?我的猜測是我只是茉莉花和單元測試的新手。