Reputation: 1665
Below is the code for part of a controller I'm trying to unit test. I hate to post something that I have not yet attempted but I'm very lost as to how I should start testing this piece of code. I think part of the problem is I'm not sure how modalInstance
is executed. If you can see a good entry point please let me know.
$scope.confirmDelete = function (account) {
var modalInstance = $modal.open({
templateUrl: '/app/accounts/views/_delete.html',
controller: function (global, $scope, $modalInstance, account) {
$scope.account = account;
$scope.delete = function (account) {
global.setFormSubmitInProgress(true);
accountService.deleteAccount(global.activeOrganizationId, account.entityId).then(function () {
global.setFormSubmitInProgress(false);
$modalInstance.close();
},
function (errorData) {
global.setFormSubmitInProgress(false);
});
};
$scope.cancel = function () {
global.setFormSubmitInProgress(false);
$modalInstance.dismiss('cancel');
};
},
resolve: {
account: function () {
return account;
}
}
});
Upvotes: 0
Views: 76
Reputation: 2214
To start with, to make it properly testable, you might want to extract the nested controller to a first-class controller in the same angular module as this.
You can then test this current controller ( call it CtrlA) up to the point of confirmDelete
and then test the newly extracted, so to say, 'modal controller' (lets call CtrlB) it separately.
In other words, in your tests for CtrlA, you ought to invoke confirmDelete
and expect $modal.open toHaveBeenCalled
. Note that in these tests, you would mock $modal.open
:
spyOn(modal, 'open');
Under the hood, angular-ui-bootstrap instantiates a modal and sets up all the references correctly so that $modalInstance
injected in CtrlB is same as modalInstance in your CtrlA that $modal.open
returns. Since this is third party code, you need not 'test' the validity of this claim through your unit tests. You unit tests would simply assume that $modalInstance
CtrlB has received is same as that created in CtrlA.
All that is left now is for you to test that each of the scope methods in CtrlB behave the way you them to. For that, you would create a spy object and inject it into the CtrlB as $modalInstance
and you'd go about writing test as if you were writing tests for any ordinary controller.
For example, invoke cancel
and test whether the spy $modalInstance.dismiss
has been called (and so forth)
Best of luck!
Upvotes: 1