I'm currently working on writing unit tests for a controller that receives a promise from a service. However, when using Jasmine, I encounter the following error:
TypeError: Cannot read property 'then' of undefined
Within the controller, I am trying to use .then()
on the promise returned by the service.
Can anyone provide assistance? I must be overlooking something obvious.
Here is a link to the plunk: http://plnkr.co/edit/vJOopys7pWTrTQ2vLgXS?p=preview
'use strict';
describe('Language controller', function() {
var scope, translationService, createController;
beforeEach(function() {
var mockTranslationService = {};
module('dictApp', function($provide) {
$provide.value('translationService', mockTranslationService);
});
inject(function($q) {
mockTranslationService.languages = [
{
name: 'slovak'
},
{
name: 'czech'
}
];
mockTranslationService.languagesWithWords = [{
name: 'slovak',
words: [{
key: 'Car',
translation: 'Auto',
createdOn: 0
}, {
key: 'Flower',
translation: 'Kvet',
createdOn: 0
}]
}, {
name: 'czech',
words: {
key: 'Plaza',
translation: 'Namesti',
createdOn: 0
}
}];
mockTranslationService.getLanguages = function() {
var deferred = $q.defer();
deferred.resolve(this.languages);
return deferred.promise;
};
});
});
beforeEach(inject(function($controller, $rootScope, _translationService_) {
scope = $rootScope.$new();
translationService = _translationService_;
createController = function () {
return $controller('LanguageCtrl',
{$scope: scope, translationService: translationService});
};
scope.$digest();
}));
it('should retrieve the language array', function() {
spyOn(translationService, 'getLanguages');
createController();
expect(translationService.getLanguages).toHaveBeenCalled();
});
});
And here is the controller code:
dictControllers.controller('LanguageCtrl', ['$scope', 'translationService', function($scope, translationService){
$scope.getLanguages = function() {
translationService.getLanguages().then(function(){
$scope.languages = translationService.languages;
});
};
$scope.getLanguages();
$scope.getWords = function(language) {
translationService.getWords(language);
};
$scope.newWord = {};
$scope.addWord = function(language) {
translationService.addWord($scope.newWord, language);
$scope.newWord = {};
};
}]);