Reputation: 443
I am finally working on learning how to test using an older angularjs app I wrote. I have a few modals in my controller and I cannot figure out for the life of me how to make sure the code in 'modalInstance.result.then' is run and test against it.
I've searched Google and SO and have found examples of people testing their modals but so far they all seem to involve testing the modal controller itself.
How to I get that promise (modalInstance.result.then) to resolve? I've tried running $modal.close() but that fails to an error. I've tried mocking modalInstance and $modal in a number of ways, using jasmine spys, etc. My ignorance when it comes to testing is holding me up. Any help would be appreicated.
Here is my controller.js:
(function() {
var comment = angular.module('APP.comment', ['APP.user']);
var commentController = function($scope, $modal) {
var self = this;
self.addComment = function(newComment) {
var modalInstance = $modal.open({
templateUrl: 'views/commentModal.html',
backdrop: 'static',
windowClass: 'modal',
controller: 'commentModalController',
controllerAs: 'commentCtrl',
resolve: {
newComment: function() {
return newComment;
}
}
});
modalInstance.result.then(function(data) {
// How do I test that the function or branches here
// were run?
if (data.length === 2) {
// do this thing
} else {
// do this other thing
}
});
};
};
commentController.$inject = ['$scope', '$modal'];
comment.controller('commentController', commentController);
}());
Here is the test I have so far:
describe('Unit: commentController', function() {
var $rootScope,
$scope,
$controller,
$modal;
beforeEach(module('APP.comment'));
beforeEach(inject(function(_$rootScope_, _$controller_, _$modal_) {
$modal = _$modal_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$controller = _$controller_('commentController as commentCtrl', {
$scope: $scope,
$modal: $modal,
});
}));
it('should have controller defined', function() {
expect($scope.qaCtrl).toBeDefined();
});
it('should have method defined', function() {
expect($scope.qaCtrl.addComment).toBeDefined();
});
describe('$scope.commentCtrl.addComment', function() {
it('should open modal', function() {
$scope.commentCtrl.addComment();
});
});
});
I have a plnkr here:
http://plnkr.co/edit/YtYVPReH9yysZXPjbsC0?p=preview
Upvotes: 2
Views: 4283
Reputation: 691635
it('should open modal', inject(function($q) {
var fakeResult = {
result: $q.when([])
};
spyOn($modal, 'open').and.returnValue(fakeResult);
$scope.commentCtrl.addComment();
$scope.$apply();
// now check that the right thing has been done, given the empty array returned
}));
Upvotes: 3