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

流过昼夜 提交于 2019-12-08 14:45:55

问题


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?


回答1:


Try sending out the event yourself.

$rootScope.$broadcast('$routeChangeSuccess', eventData);



回答2:


A more behaviour driven approach is to do an actual navigation using

$location.url() or $location.path()

In order for this to work you need to do two things in your test:

  1. you need to inject $route (even if you're not using it). This is, because $route adds an internal listener for $locationChangeStart, but it will only do so when $route is requested somewhere (and thus initialized)

  2. you need to provide a dummy routing that you can navigate to:

    beforeEach(module(function($routeProvider) {
         $routeProvider.when('/somePath', { template: ' ' });
    }));
    


来源:https://stackoverflow.com/questions/22447988/how-to-mock-trigger-a-routechangesuccess-in-angular-unit-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!