I have a problem with the following situation:
I have a Controller that does a service call to get the different available languages and their greetings. And I would like to test this controller, I have based the test I've written from the following sites and articles:
Angular unit-test controllers - mocking service inside controller
http://jasmine.github.io/2.2/introduction.html
and ofcourse AngularJs documentations
But I have a feeling that i am doing some things wrong or overdoing my tests.
In the ones i have writted, the first 3 pass, but the 4th one (in my eyes the most important one) fail.
Could someone be so kind to help me out or point me in the right direction. It seems like every article I read says something different on what and how to test.
Controller
angular.module('app')
.controller('MainCtrl', function ($scope, LanguagesService) {
$scope.languages = LanguagesService.getAll();
});
Service
angular.module('app')
.factory('LanguagesService', function () {
var lang = {};
lang.greetings = [
'Welkom bij,',
'Bienvenu chez'
];
lang.languages = [
{
name: 'Nederlands',
code: 'nl'
},
{
name: 'Français',
code: 'fr'
}
];
return {
getAll: function () {
return lang;
}
};
});
My unit test for the controller
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('app'));
var MainCtrl,
scope,
LanguagesService;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, _LanguagesService_) {
scope = $rootScope.$new();
LanguagesService = _LanguagesService_;
MainCtrl = $controller('MainCtrl', {
$scope: scope,
'LanguagesService': LanguagesService
});
/*
* Spy on service
*/
spyOn(LanguagesService, 'getAll');
}));
/*
* Test 1: Is this test overkill ? As the tests wont run if the service is not injected
*/
it('should get an instance of LanguagesService', function() {
expect(LanguagesService).toBeDefined();
});
it('should attach languages to the scope', function() {
expect(scope.languages).not.toBe(null);
});
it('should have the same amount of languages as greetings', function() {
expect(scope.languages.languages.length).toBe(scope.languages.greetings.length);
});
/*
* Test 4: This test fails
*/
it('should have called LanguagesService method getAll', function() {
expect(LanguagesService.getAll).toHaveBeenCalled();
});
});