[英]How to unit test Angular routeChangeSuccess in directive link function?
因果关系不断抛出TypeError: Cannot read property 'originalPath' of undefined
在link
函数中使用以下命令TypeError: Cannot read property 'originalPath' of undefined
:
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和单元测试。
我最终想出了如何使用$route.reload()
触发路由更改
从文档中 ,它:
即使$ location保持不变,也使$ route服务重新加载当前路由。 结果,ngView会创建新的作用域并重新实例化控制器。
因此,将其添加到我的测试中可以“重新引导”路由,从而迫使routeChangeSuccess发出并在被消化后传递到link
。 这是spec文件中的更新块,其中添加了$ location更改以测试其他路由:
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');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.