LikeMaBell LikeMaBell - 1 month ago 6
AngularJS Question

How to inject $routeProvider in Angular spec

When passing this function that includes $routeProvider into a module definition, how do you mock/inject it properly in spec?

module.js

angular.module('myModule', [
// Without the function($routeProvider) below the test passes. With it, it fails.
function($routeProvider) {
$routeProvider.when('/some/url/:id', {templateUrl: 'template.html', reloadOnSearch: false});
}
])


myModuleCtrl.js

angular.module('myModule')
.controller('myModuleCtrl', [
'$scope',
function ($scope) {
$scope.testMethod = function () {
alert('Test Me!');
}
}
]);


myModuleCtrl.spec.js

describe('myModuleCtrl', function () {
var controller;
var $scope;

beforeEach(angular.mock.module('myModule'));
beforeEach(function () {
$scope = {};
});
beforeEach(angular.mock.inject(function ($rootScope, $controller) {
controller = $controller('myModuleCtrl', {'$scope': $scope});
}));

describe('when doing stuff', function() {
it('does other stuff', function() {
$scope.testMethod();
});
});
});


As commented in module.js, without the $routeProvider line the spec passes. With it, it fails with the following message:

Error: [$injector:modulerr] Failed to instantiate module myModule due to:
Error: [$injector:modulerr] Failed to instantiate module function ($routeProvider) due to:
Error: [$injector:unpr] Unknown provider: $routeProvider


What needs to be done in the spec file to get this module to load (including the $routeProvider)?

Answer

Your module should have injected dependency ngRoute

angular.module('myModule', ['ngRoute'])

Samething should be there for the test,

beforeEach(angular.mock.module('myModule',['ngRoute']));