我正在尝试模拟路由更改成功以便编写测试。使用routeProvider注册了一个url,即'example /:id'。
$scope.$on('$routeChangeSuccess', function(angularEvent, current, previous) {
var super_important_id = current.pathParams.id
// Do something with super_important_id
})
我试过
$location.path('/example/0')
$rootScope.$apply();
$rootScope.$broadcast('$routeChangeSuccess')
但是当我运行测试时它总是抛出这个错误
TypeError: 'undefined' is not an object (evaluating 'current.pathParams')
如何成功模拟路线更改成功事件并使其填写pathParams?
答案 0 :(得分:2)
如果您手动广播$routeChangeSuccess
事件,则需要为其提供参数。像这样:
var objToMockCurrentRoute = {
pathParams: {
id: "MY_ID"
//any other needed properties
}
//any other needed properties
}
$rootScope.$broadcast('$routeChangeSuccess', objToMockCurrentRoute);
如果不这样做,current
只是undefined
,这就解释了您所看到的错误。
此外,这样做意味着您无需致电$location.path
。