问题
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:
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)
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