THE ISSUE AT HAND:
In my Angular / Ionic app, I am currently in the process of testing a modal to ensure it is functioning correctly.
While I have successfully tested that the modal opens as expected, I am facing difficulties in testing the proper closing of the modal.
Despite multiple attempts and researching similar inquiries, I have yet to find a viable solution.
THE CODE IN QUESTION:
The controller:
The code functions properly within the application but has been refactored for ease of unit testing.
$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 initial test (opening the modal) executes smoothly and passes. However, I am stuck on how to proceed with the second test.
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 ENCOUNTERED:
An error message stating:
TypeError: Cannot read property 'hide' of undefined
THE QUERY:
I am seeking guidance on how to effectively test the closure of the modal.
How can I confirm that the hide()
function has been executed correctly?
Is the issue related to how the modal is declared in the test?
Thank you for your assistance!
UPDATE:
This response adequately addresses the query regarding testing the closure of a modal by suggesting a proper solution to include before opening the modal. For insights on efficiently spying on a modal, a separate inquiry has been raised:
Karma-Jasmine: How to properly spy on a Modal?
The provided answer also offers a guideline on general premise spying techniques.