Angularjs – How to unit test angularjs controller with $location service

angularjsunit testing

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

Best Answer

This is how my test ended up working.

describe('OpponentsCtrl', function() {
    var scope, rootScope, ctrl, location;

    beforeEach(inject(function($location, $rootScope, $controller) {
        location = $location;
        rootScope = $rootScope;
        scope = $rootScope.$new();
        ctrl = $controller(OpponentsCtrl, {$scope: scope});
    }));

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

        // test whatever the service should do...
        scope.show('/test');
        expect(location.path()).toBe('/test');

    });
});