I am delving into the realm of unit testing in Angular. Starting off by writing tests for my controllers and then moving on to testing my services.
Initially, I began with a simple test.
This is the controller code:
angular.module('app')
.controller('TestCtrl', function ($rootScope,$scope,fileLoader,ngProgress) {
$scope.test= [];
$scope.init = function(){
fileLoader.getFile("test")
.then(function(res){
//Success
console.log(res);
$scope.test= res;
}, function(err){
//Error
});
ngProgress.complete();
}
$scope.init();
$scope.title = "Test";
});
This is the corresponding test code:
describe('Controller: TestCtrl', function () {
// load the controller's module
beforeEach(module('app'));
var TestCtrl,
scope,test;
test = {};
test.getFile = function(name) {
return [
{
"id": 0,
"name": "Test",
"imgName": "Test.png"
},
{
"id": 1,
"name": "Test1",
"imgName": "Test1.png"
}];
};
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
TestCtrl= $controller('TestCtrl', {
$scope: scope,
fileLoader : test
});
}));
it('should have the correct title', function () {
expect(scope.title).toBe("Test");
});
});
After running the test, I encountered an error that reads:
TypeError: 'undefined' is not a function (evaluating 'fileLoader.getFile("test") .then') undefined
I am puzzled as to why I am getting this error despite injecting the necessary dependencies. Is there a way to organize my mocks in a separate file, such as my fileLoader mock, and inject them more efficiently?
The confusion lies in how I am injecting the dependencies but still facing issues with undefined values.
Thank you for your help!