How to mock $ location when unit testing in angularjs

Here is my run block, where I set a couple of properties on rootScope based on the location path:

 angular.module('xyz').run(['$rootScope', '$location', '$route', function($rootScope, $location, $route){ $rootScope.brand = $location.path().split('/')[1]; $rootScope.appName = $rootScope.brand.split('.')[2]; }); 

Here's a unit test that doesn't work:

 beforeEach(module('App')); beforeEach( inject( function( $controller, _$location_, $rootScope) { $location = _$location_; $scope = $rootScope.$new(); AppCtrl = $controller( 'AppCtrl', { $location: $location, $scope: $scope }); })); it('AppCtrl has been initialized', inject( function() { expect( AppCtrl ).toBeTruthy(); })); 

Tried something on these lines:

 it('should set the default category to match the category_id found in location.hash', function() { $browser.setUrl('http://server/#/categories/2'); $browser.poll(); scope.$eval(); $browser.xhr.flush(); expect(ctrl.selectedCategory).toBe('2'); }); 

Did not help.

+7
angularjs unit-testing
source share
1 answer

Here is your solution https://groups.google.com/d/msg/angular/F0jFWC4G9hI/FNz3oQu0RhYJ .

To inform you about this, Igor Minar and Vojta Gina are the developers of Angular, and the latter is one of the main individuals performing unit tests of AngularJs, so pay attention to them.

So, basically he already uses the mocked version of the $location service during testing, and you should be able to fully control it.

+7
source share

All Articles