使用routeChangeSuccess测试控制器但缺少参数

时间:2014-09-08 20:18:28

标签: angularjs unit-testing jasmine

我正在尝试模拟路由更改成功以便编写测试。使用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?

1 个答案:

答案 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