angularjs route unit testing
Why not just assert the route object is configured correctly?
it('should map routes to controllers', function() { module('phonecat'); inject(function($route) { expect($route.routes['/phones'].controller).toBe('PhoneListCtrl'); expect($route.routes['/phones'].templateUrl). toEqual('partials/phone-list.html'); expect($route.routes['/phones/:phoneId'].templateUrl). toEqual('partials/phone-detail.html'); expect($route.routes['/phones/:phoneId'].controller). toEqual('PhoneDetailCtrl'); // otherwise redirect to expect($route.routes[null].redirectTo).toEqual('/phones') });});
I think you should be able to test the $routeProvider like this:
angular.module('phonecat', []). config(['$routeProvider', function($routeProvider) { $routeProvider. when('/phones', {templateUrl: 'partials/phone-list.html', controller: PhoneListCtrl}). when('/phones/:phoneId', {templateUrl: 'partials/phone-detail.html', controller: PhoneDetailCtrl}). otherwise({redirectTo: '/phones'});}]);it('should test routeProvider', function() { module('phonecat'); inject(function($route, $location, $rootScope) { expect($route.current).toBeUndefined(); $location.path('/phones/1'); $rootScope.$digest(); expect($route.current.templateUrl).toBe('partials/phone-detail.html'); expect($route.current.controller).toBe(PhoneDetailCtrl); $location.path('/otherwise'); $rootScope.$digest(); expect($location.path()).toBe('/phones/'); expect($route.current.templateUrl).toEqual('partials/phone-list.html'); expect($route.current.controller).toBe(PhoneListCtrl); });});
Combining the two previous answers, if you want to test the router as a black box that is successfully routing where it should (not the controller ets configs in themselves), whatever the routes might be:
// assuming the usual inject beforeEach for $route etc.var expected = {};it('should call the right controller for /phones route', function () { expected.controller = $route.routes['/phones'].controller; $location.path('/phones'); $rootScope.$digest(); expect($route.current.controller).toBe(expected.controller);});it('should redirect to redirectUrl from any other route', function () { expected.path = $route.routes[null].redirectTo; $location.path('/wherever-wrong'); $rootScope.$digest(); expect($location.path()).toBe(expected.path);});