Currently i got stuck in writing a unit test for my angular controller. I have a $scope Function which makes an ajax request and after resolving all promises it assigns the fetched data to $scope.products. But it does not work for me and i don't know what i'm doing wrong here!
controller
$scope.products = [];
// $q.all is used because i've some other data sources too
$scope.query = function (term) {
$q.all([
DataService.autocomplete.products(term)
]).then(function (results) {
$scope.products = results[0].data.content;
});
};
Dataservice
// dataservice return value
return {
autocomplete: {
products: function (term) {
// _makeRequest is a wrapper for a $http call
return _makeRequest('autocomplete/products', term);
}
}
}
Unit-Test
describe('[Autocomplete] AutocompleteCtrl', function () {
var $scope, DataService;
beforeEach(module('Autocompleter'));
beforeEach(inject(function ($rootScope, $controller, _$q_, _DataService_) {
var deferred = _$q_.defer();
$scope = $rootScope.$new();
DataService = _DataService_;
$controller('AutocompleteCtrl', {$scope: $scope});
deferred.resolve(['resolveData']);
spyOn(DataService.autocomplete, 'products').and.returnValue(deferred.promise);
}));
describe('Query', function () {
it('should resolve promise', function () {
$scope.query('term');
$scope.$apply();
expect($scope.products).toBe(['resolveData']);
});
});
});
Test-Result
TypeError: 'undefined' is not an object (evaluating 'results[0].data.content')