simonvogensen simonvogensen - 24 days ago 13
AngularJS Question

How to unit test angularjs controller with $location service

I am trying to create a simple unit test that tests my show function.

I get the following error:

TypeError: Object #<Object> has no method 'show'


It seems like
$rootScope
isn't the scope of the controller?

Here's my controller:

function OpponentsCtrl($scope, $location) {
$scope.show = function(url) {
$location.path(url);
}
}
OpponentsCtrl.$inject = ['$scope', '$location'];


Here's my controller unit test:

describe('OpponentsCtrl', function() {
beforeEach(module(function($provide) {
$provide.factory('OpponentsCtrl', function($location){
// whatever it does...
});
}));

it('should change location when setting it via show function', inject(function($location, $rootScope, OpponentsCtrl) {
$location.path('/new/path');
$rootScope.$apply();
expect($location.path()).toBe('/new/path');

$rootScope.show('/test');
expect($location.path()).toBe('/test');
}));
});

Answer

Why don't you simply use a spyOn function?

describe('OpponentsCtrl', function() {

    var location;

    beforeEach(module(function($provide) {
        $provide.factory('OpponentsCtrl', function($location){
            location = $location;
        });
    }));

    it('should change location when setting it via show function', inject(function() {    
        spyOn(location, 'path');    
        expect(location.path).toHaveBeenCalledWith('/new/path');
    }));
});

Hope this helps!

Comments