Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock/trigger a $routeChangeSuccess in Angular unit tests?

Given a handler attached to the $routeChangeSuccess event to update the title property on $rootScope:

$rootScope.$on('$routeChangeSuccess', function (event, current, previous) {
  $rootScope.title = 'My title';
});

in unit tests, I expect that performing a route change would update the title property:

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

  expect($rootScope.title).toBe('My title');
});

However, the code in the $routeChangeSuccess handler never executes in tests. It executes fine and updates the title when running the application in the browser.

How can I trigger a $routeChangeSuccess event in tests? Is there a better approach to testing any arbitrary code that is attached to $rootScope.$on('$routeChangeSuccess', ...) or other $routeChange events?

like image 813
user2943490 Avatar asked Mar 17 '14 06:03

user2943490


1 Answers

Try sending out the event yourself.

$rootScope.$broadcast('$routeChangeSuccess', eventData);
like image 186
Anders Ekdahl Avatar answered Oct 21 '22 17:10

Anders Ekdahl