As a newcomer to testing, I am attempting to write Jasmine/Karma tests for a controller. Given a sample test to use as a starting point, the issue arises when passing the $controller
in the argument of the it
block. The test passes successfully with this setup.
While writing tests for other controllers within the app, I have not encountered the need to pass $controller
before. Following my usual practice, upon removing $controller
, the test fails due to missing dependencies (which should ideally be provided via $provide.value
in the beforeEach
...?).
The code snippet for the controller is as follows:
(function() {
'use strict';
angular
.module('myApp')
.controller('EntryAddController', EntryAddController);
function EntryAddController($scope, $state, moment, $sanitize, dogList, catList, months, frequencies, EntryFactory, $modal, toastr, $log) {
var vm = this;
// Additional logic here
})();
Below is the given sample code including the it
block:
(function() {
'use strict';
describe('Entry Add Controller', function(){
describe('EntryAddController', function() {
var vm, $rootScope, $controller;
beforeEach(module('myApp'));
beforeEach(function() {
inject(function(_$rootScope_, _$controller_) {
$rootScope = _$rootScope_;
$controller = _$controller_;
});
});
describe('EntryAddController', function() {
var $scope;
beforeEach(function createChildScopeForTheTest() {
$scope = $rootScope.$new();
});
afterEach(function disposeOfCreatedChildScope() {
$scope.$destroy();
});
it('expects fromDate and toDate to be defined', function($controller) {
vm = $controller('EntryAddController', { $scope: $scope });
expect(vm.fromDay).toBeDefined();
});
});
});
});
})();
The removal of $controller
from the function argument in the it
block results in the following error:
Error: [$injector:unpr] Unknown provider: dogListProvider <- dogList <- EntryAddController
What sets apart these two versions of the it
block?
it('expects fromDate and toDate to be defined', function($controller) {
vm = $controller('EntryAddController', { $scope: $scope });
expect(vm.fromDay).toBeDefined();
});
vs.
it('expects fromDay to be defined', function() {
vm = $controller('EntryAddController', { $scope: $scope });
expect(vm.fromDay).toBeDefined();
});