i have some issues when i try to test controller which uses promises with jasmine.
I have following jasmine test:
describe('Testing a controller', function () {
var $scope, $root, ctrl, $q, deferred;
var MockService;
beforeEach(function () {
module('myApp');
inject(function ($rootScope, $controller, $q) {
$root = $rootScope;
$scope = $rootScope.$new();
MockService = {
fetch: function () {
return {
get: function () {
deferred = $q.defer();
return {
$promise: deferred.promise
};
}
};
}
};
ctrl = $controller('myController', {
$scope: $scope,
$root: $rootScope,
MyService: MockService,
});
});
spyOn(MockService, 'fetch').andCallThrough();
});
it('Get data from promise', function () {
$scope.init();
deferred.resolve("It worked!");
$root.$digest();
expect(MockService.fetch).toHaveBeenCalled();
expect($scope.test).toBe('It worked!');
});
});
and this is the controller:
controllers.controller('myController', ['$scope','MyService'
function ($scope, myService) {
$scope.init = function () {
myService.fetch().get().$promise.then(function (data) {
$scope.test = data;
}, function (error) {
$scope.error = error;
});
};
}
]);
And the test keeps failing: "Expected undefined to be 'It Worked!'."
It seems that the promise gets resolved and "then" function is never called. Any ideas what's the issue ?