我正在尝试以 Angular Testing 模态的打开,但遇到此错误:
Error: Unexpected request: GET app/templates/editComment/editComment.html
No more request expected
这是我正在测试的代码:
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();
});
}
测试设置:
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 });
}));
这是我的测试:
it('edit comments should open modal', inject(function () {
var comment = "test";
ctrl.editComment(comment);
scope.$apply();
expect(modalInstance.open).toHaveBeenCalled();
}));
我都看过 Testing AngularUI Bootstrap modal instance controller和 Mocking $modal in AngularJS unit tests试图得到一些答案,但到目前为止我尝试过的都没有奏效。
如有任何帮助,我们将不胜感激。
最佳答案
Modal.open 需要返回一个 promise ,但也需要成为一个 spy ,以防您不想要结果。
如果我们只这样做:
open: jasmine.createSpy('modal.open')
它适用于大多数情况,但我们需要一个 promise ,所以如果我们这样做:
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 });
}));
它应该像魅力一样发挥作用!
关于javascript - 使用 Jasmine 在 Angular 中模拟 Modal 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34203418/