I have the following controller defined in Angular JS that uses a service from Angular Material:
angular.module('leopDirective', [])
.controller('MenuCtrl', function ($scope, $timeout, $mdSidenav, $log)
{
$scope.mdSidenav = $mdSidenav;
$scope.close = function () {
$mdSidenav('left').close().then(function () {
$log.debug("close LEFT is done");
$scope.closed = true;
});
};
});
It depends on the service $mdSidenav that I am trying to mock with my own factory object:
describe('Controller: MenuCtrl', function() {
var $rootScope, $scope, $controller, $q, menuCtrl,
mock__mdSidenav = function(component) {
return {
isMock: true,
component: component,
close: function () {}
}
};
beforeEach(function () {
module('leopDirective', function($provide) {
$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 () {
expect($scope.mdSidenav).toBeDefined();
});
describe('managing $mdSidenav', function () {
it('should close the menu', function () {
var data, deferred = $q.defer(), promise = deferred.promise;
mock__mdSidenav.close = function() {
return promise.then(function (response) {
data = response.success;
});
};
$rootScope.$digest();
$scope.close();
});
});
I have the code in the following plnkr.
Apparently, the only thing that it is not working is my assignment of the $promise to the close() within the second "describe" block of the test. The execution of this test returns the following error:
TypeError: Cannot read property 'then' of undefined
TypeError: Cannot read property 'then' of undefined
at Scope.$scope.close (app.js:7:35)
What makes me think that either the factory itself or the promise function are not correctly mocked up.
- Is this the correct way for mocking a factory?
- Is this the correct way for creating method that returns a promise?
Aucun commentaire:
Enregistrer un commentaire