Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock $location when Unit testing in angularjs

Here's 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 the unit test that's failing:

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 along 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'); 
}); 

Didn't help.

like image 913
Chandra Avatar asked Oct 02 '13 17:10

Chandra


People also ask

What is mocking in unit testing Angular?

A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.

What is $location in AngularJS?

The $location in AngularJS basically uses a window. location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in AngularJS.

Can we write unit test cases for Angular?

Angular Unit testing is the process of testing small and isolated pieces of code in your Angular application. This provides an added advantage to the users in the sense that they can add any new features without breaking any other part of their application.

Which one is used to run the unit tests in Angular?

Jasmine is the default test framework used with Angular.


1 Answers

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

Just to let you know, Igor Minar and Vojta Jína are both Angular developers and the latter is one of the main persons behind AngularJs unit testing, so pay attention to them.

So, basically it already uses a mocked version of the $location service while in test and you should be able to perfectly control it.

like image 103
Caio Cunha Avatar answered Oct 24 '22 17:10

Caio Cunha