solo solo - 3 months ago 26
AngularJS Question

Injecting routerProvider for AngularJS test using Jasmine

I'm using Jasmine for testing AngularJS controller and I'm struggling to find a way of injecting $routeProvider into the module.

Here's my controller:

var app = angular.module('testApp', []);

app.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.
when('/smth', {
templateUrl: 'smth.html',
controller: 'testController'
});
}]);

app.controller('testController', ['$scope', function ($scope) {
$scope.data = 'GG';
}]);


Here's my test:

describe('Test Suite', function () {
var myScope, ctrl;

beforeEach(module('testApp'));

beforeEach(inject(function ($controller, $rootScope) {
myScope = $rootScope.$new();
ctrl = $controller('testController', {
$scope: myScope
});
}));

it('data is GG', function () {
expect(myScope.data).toEqual('GG');
});
});


When I try to run it, I receive a following error:

Error: [$injector:modulerr] Failed to instantiate module testApp due to:
Error: [$injector:unpr] Unknown provider: $routeProvider


But if I try to run again - I get this:

TypeError: 'undefined' is not an object (evaluating 'myScope.data')


Errors keep alternating if tests are run again. I'm using Visual Studio 2013 and Resharper 8 to run the Jasmine tests.

Answer

Add the angular-route bower component to your project and then inject the ngRoute into your module like this

var app = angular.module('testApp', ['ngRoute']);
app.config(['$routeProvider', function ($routeProvider) {
  $routeProvider.
      when('/smth', {
          templateUrl: 'smth.html',
          controller: 'testController'
      });
}]);

app.controller('testController', ['$scope', function ($scope) {
    $scope.data = 'GG';
}]);