I am currently working on unit testing an AngularJS controller using Karma and Jasmine.
Below is the test suite I have created:
describe('Controllers', function(){
var $scope, ctrl;
beforeEach(module('curriculumModule'));
describe('CreateCurriculumCtrl', function(){
var mockBackend, location;
beforeEach(inject(function($rootScope, $controller, _$httpBackend_, $location){
mockBackend = _$httpBackend_;
location = $location;
$scope = $rootScope.$new();
ctrl = $controller('CreateCurriculumCtrl', {
$scope: $scope
});
}));
it('should successfully save the curriculum', function(){
mockBackend.expectPost('bignibou/curriculum/new');
$scope.saveCurriculum();
mockBackend.flush();
expect(location.path()).toEqual("/");
});
});
});
The output from running karma start is as follows:
PhantomJS 1.9.2 (Linux) Controllers CreateCurriculumCtrl should successfully save the curriculum FAILED
TypeError: 'undefined' is not a function (evaluating 'mockBackend.expectPost('bignibou/curriculum/new')')
at /home/julien/Documents/projects/site-garde-enfants/bignibou/karma/test/spec/curriculum.test.js:16
PhantomJS 1.9.2 (Linux): Executed 2 of 2 (1 FAILED) (0.203 secs / 0.023 secs)
I'm struggling to understand why this error is occurring, given that I have correctly included the angular-mock.js file in my karma configuration:
// list of files / patterns to load in the browser
files: [
'../src/main/webapp/js/libs/jquery-1.10.2.js',
'../src/main/webapp/js/libs/angular.js',
'../src/main/webapp/js/libs/bootstrap.js',
'../src/main/webapp/js/plugins/angularui.select2.js',
'test/vendor/angular-mocks.js',
'../src/main/webapp/js/custom/curriculum.js',
'test/spec/curriculum.test.js'
],
If anyone could provide some assistance, it would be greatly appreciated.
Edit: Here is the code for my controller:
function CreateCurriculumCtrl($scope, $http, $location, select2Options){
$scope.formData={};
$scope.select2Options = select2Options;
$scope.saveCurriculum = function(){
$http.post('bignibou/curriculum/new', $scope.formData).success(function(data) {
if(data.status=="OK"){}
if(data.status=="KO"){}
$location.path("/");
});
};
}