THE SITUATION:
I am testing the proper working of a modal in my Angular / Ionic app.
So far I can properly test the fact that the modal has been called, but I don't know how to test the proper closing of the modal.
Have made several attempts and read similar questions, but didn't find a solution.
THE CODE:
The controller:
Code working fine in the app, it has just been refactored to facilitate the unit test.
$scope.open_login_modal = function()
{
var temp = $ionicModal.fromTemplateUrl('templates/login.html',{scope: $scope});
temp.then(function(modal) {
$scope.modal_login = modal;
$scope.modal_login.show();
});
};
$scope.close_login_modal = function()
{
$scope.modal_login.hide();
};
The test:
The first test (open modal) is working fine and passes. The second test I don't know how to do it.
describe('App tests', function()
{
beforeEach(module('my_app.controllers'));
// mocking the .then method of $ionicModal.fromTemplateUrl (it works)
function fakeTemplate()
{
return {
then: function(modal){
$scope.modal_login = modal;
}
}
}
beforeEach(inject(function(_$controller_, _$rootScope_)
{
$controller = _$controller_;
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
$ionicModal =
{
fromTemplateUrl: jasmine.createSpy('$ionicModal.fromTemplateUrl').and.callFake(fakeTemplate)
};
var controller = $controller('MainCtrl', { $scope: $scope, $rootScope: $rootScope, $ionicModal: $ionicModal });
}));
describe('Modal tests', function()
{
it('should open login modal', function()
{
$scope.open_login_modal();
expect($ionicModal.fromTemplateUrl).toHaveBeenCalled();
expect($ionicModal.fromTemplateUrl.calls.count()).toBe(1);
});
it('should close login modal', function()
{
$scope.close_login_modal();
// How can i test here that the modal has been close?
});
});
});
THE ERROR:
This is the error message: TypeError: Cannot read property 'hide' of undefined
THE QUESTION:
How can I test the close of the modal?
How can I be sure that the function hide()
has been properly called?
It has to do with the declaring of the modal in the test?
Thank you very much!
EDIT:
This answer properly replied to the question 'how to test the closing of a modal' giving the right solution to include before the opening of the modal. If you want to know how to properly spy a modal i have asked in a separate question:
Karma-Jasmine: How to properly spy on a Modal?
The given answer give also the rule how to spy a premise in general.