Encountering a challenge with Karma throwing
TypeError: Cannot read property 'originalPath' of undefined
while working on a directive. Here is the code snippet within the link
function:
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';
});
}
}
Alongside this, there is a unit test block included:
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');
});
});
The issue arises when attempting to log the curr
route from within the link, as it returns
Object{params: Object{}, pathParams: Object{}, locals: Object{}}
. There have been attempts to pass a mock route to the broadcasted message, but no changes were observed. Seeking advice on how to obtain the expected default route for passing into the directive. Is this approach correct for tracking a route change within a link? It is suspected that unfamiliarity with Jasmine and unit testing might be contributing to the challenge.