Reputation: 641
I'm trying to test the opening of a modal in angular but running into this error:
Error: Unexpected request: GET app/templates/editComment/editComment.html
No more request expected
Here's my code I'm testing:
vm.editComment = function (comment) {
vm.modalInstance = $modal.open({
templateUrl: 'app/templates/editComment/editComment.html',
controller: 'EditCommentCtrl as vm',
comment: comment,
resolve: {
comment: function () {
return comment;
}
}
}).result.then(function (result) {
vm.getComments();
});
}
Test Setup:
beforeEach(inject(function ($rootScope, $controller, $q, $sce) {
q = $q;
var stateParam = {id: 1};
scope = $rootScope.$new();
var Listmanager = "";
var fakeModal = {
result: {
then: function(confirmCallback, cancelCallback) {
//Store the callbacks for later when the user clicks on the OK or Cancel button of the dialog
this.confirmCallBack = confirmCallback;
this.cancelCallback = cancelCallback;
}
},
close: function( item ) {
//The user clicked OK on the modal dialog, call the stored confirm callback with the selected item
this.result.confirmCallBack( item );
},
dismiss: function( type ) {
//The user clicked cancel on the modal dialog, call the stored cancel callback
this.result.cancelCallback( type );
}};
var modalInstance = {
open: jasmine.createSpy('modalInstance.open')
}
modalInstance.open.and.returnValue(fakeModal);
ctrl = $controller('CommentsCtrl', { $scope: scope, $modalInstance: modalInstance, ds: dsMock, $stateParams: stateParam, $sce: $sce, Listmanager: Listmanager, ns: nsMock });
}));
Here's my test:
it('edit comments should open modal', inject(function () {
var comment = "test";
ctrl.editComment(comment);
scope.$apply();
expect(modalInstance.open).toHaveBeenCalled();
}));
I've looked at both Testing AngularUI Bootstrap modal instance controller and Mocking $modal in AngularJS unit tests to try and get some answers but nothing that I've tried has worked so far.
Any help would be appreciated.
Upvotes: 0
Views: 5638
Reputation: 797
Modal.open needs to return a promise, but also needs to be a spy in case you don't want a result.
If we only did:
open: jasmine.createSpy('modal.open')
it will work for most cases, but we want a promise so if we did this:
beforeEach(inject(function ($rootScope, $controller, $q, $sce) {
q = $q;
var stateParam = {id: 1};
scope = $rootScope.$new();
var Listmanager = "";
modal = {
open: jasmine.createSpy('modal.open').and.returnValue({ result: { then: jasmine.createSpy('modal.result.then') } }),
close: jasmine.createSpy('modal.close'),
dismiss: jasmine.createSpy('modal.dismiss')
};
ctrl = $controller('CommentsCtrl', { $scope: scope, $modal:modal, ds: dsMock, $stateParams: stateParam, $sce: $sce, Listmanager: Listmanager, ns: nsMock });
}));
It should work like a charm!
Upvotes: 3