I have the following controller in AngularJS that is invoking a service provided by "$mdSidenav" from Angular Material. This is service is provided by a factory method.
angular.module('leopDirective', [])
.controller('MenuCtrl', function ($scope,$timeout,$mdSidenav,$log) {
$scope.mdSidenav = $mdSidenav;
$scope.close = function () {
$mdSidenav('left').close().then(function() {$scope.closed=true; });
};
});
I am trying to mock that service ($mdSidenav) in order to test my controller. The following is the source code of the Jasmine test that I am trying to define:
describe('Controller: MenuCtrl', function() {
var $rootScope, $scope, $controller, $q, menuCtrl,
mock__mdSidenav = function(component) {
return {
// THIS FUNCTION IS EMPTY SINCE $Q IS NOT AVAILABLE
close: function() {}
}
};
beforeEach(function() {
module('leopDirective', function($provide) {
// I HAVE TO PROVIDE THE MOCK UP BEFORE INJECTING $Q
$provide.value('$mdSidenav', mock__mdSidenav);
});
inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$controller = $injector.get('$controller');
$q = $injector.get('$q');
$scope = $rootScope.$new();
});
menuCtrl = $controller("MenuCtrl", { $scope: $scope });
});
it('should create the $mdSidenav object', function() {
var deferred = $q.defer(),
promise = deferred.promise;
// NOW THAT $Q IS AVAILABLE, I TRY TO FILL UP THE FUNCTION
mock__mdSidenav.close = function() {
return promise.then(function(response){return response.success;});
};
// force `$digest` to resolve/reject deferreds
$rootScope.$digest();
// INVOKE FUNCTION TO TEST
$scope.close();
});
});
The problem that I have is that I do not know how to create a function for the mock that returns a promise:
- creating a promise depends on $q,
- $q has to be injected from within the block "inject",
- however, $provide has to be used within "module", just before "inject",
- therefore, the function that returns a promise within my mock object (mock__mdSidenav().close()), has to be empty at the before invoking "$provide" and, somehow, created later on.
With this approach, the error that I am getting is the following error (see Demo plnkr), which is telling me that creating the empty function first and filling it later does not work:
TypeError: Cannot read property 'then' of undefined
at Scope.$scope.close (app.js:7:35)
What is the correct way to mock a service that has a function that returns a promise?