如何在Angular单元测试中模拟/触发$ routeChangeSuccess?

use*_*490 16 unit-testing jasmine angularjs

给定一个附加到$ routeChangeSuccess事件的处理程序来更新$ rootScope上的title属性:

$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
  $rootScope.title = 'My title';
});
Run Code Online (Sandbox Code Playgroud)

在单元测试中,我希望执行路由更改会更新title属性:

it('should set a title on $routeChangeSuccess', function () {
  $location.path('/contacts');
  $rootScope.$apply();

  expect($rootScope.title).toBe('My title');
});
Run Code Online (Sandbox Code Playgroud)

但是,$ routeChangeSuccess处理程序中的代码永远不会在测试中执行.在浏览器中运行应用程序时,它执行正常并更新标题.

如何在测试中触发$ routeChangeSuccess事件?是否有更好的方法来测试附加到$ rootScope.$ on('$ routeChangeSuccess',...)或其他$ routeChange事件的任意代码?

And*_*ahl 24

尝试自己发送活动.

$rootScope.$broadcast('$routeChangeSuccess', eventData);
Run Code Online (Sandbox Code Playgroud)