gpt4 book ai didi

angularjs - 如何对 ui-bootstrap $uibModal 实例的结果进行单元测试?

转载 作者:行者123 更新时间:2023-12-01 13:36:15 25 4
gpt4 key购买 nike

我有一个调用 $uibModal.open 来弹出 ui-bootstrap 模式的 Controller 。 Controller 看起来像这样:

(function () {
'use strict';

angular
.module('app')
.controller('MyCtrl', myCtrl);

function myCtrl($uibModal) {
var vm = this;
vm.showModal = showModal;

vm.results = [];

function showModal() {
var modalInstance = $uibModal.open({
templateUrl: '/mymodal.html',
controller: 'ModalCtrl ',
controllerAs: 'modalCtrl',
});

modalInstance.result.then(function (myResult) {
// I want to test that my code here gets called and behaves as expected. shortened for brevity
vm.results.push(myResult);
});
}
}
})();

我已成功测试使用正确的配置选项打开模式。但是我想测试模态的结果,因为发生这种情况时会执行一些逻辑,但我似乎无法弄清楚如何 Hook 到结果或让它甚至在我的测试中执行

省略了一些设置代码的测试

(function() {
'use strict';

describe('myPageWithModal', function() {

//mock edit modal
var mockModalInstance = {
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 mockModalOptions = {
controller: 'ModalCtrl ',
controllerAs: 'modalCtrl',
templateUrl: '/mymodal.html',
}


describe('myModal', function() {
var actualModalOptions;

beforeEach(function() {
ctrl = //omitted

//set up a spy to listen for when modal dialogs are opened and return our mock modal
spyOn($uibModal, 'open').and.callFake(function(options) {
actualModalOptions = options;
return mockModalInstance;
});
});

it('should open edit modal with options', function() {
ctrl.showModal();

expect($uibModal.open).toHaveBeenCalledWith(mockModalOptions);
});


it('should close modal and execute the modalInstance.result logic', function() {

});
});
});
})();

最佳答案

考虑到 $uibModal.open 在当前规范中被模拟为返回 mockModalInstancemockModalInstance 应该为它所在的每个规范重新定义使用,并且 mockModalInstance.result 应该是一个 promise :

var modalResult = {};
var mockModalInstance = { result: $q.resolve(modalResult) };
spyOn(mockModalInstance.result, 'then').and.callThrough();
spyOn($uibModal, 'open').and.returnValue(mockModalInstance);

ctrl.showModal();
$rootScope.$digest();

expect(mockModalInstance.result.then).toHaveBeenCalledWith(jasmine.any(Function));
expect(ctrl.results.length).toBe(1);
expect(ctrl.results[0]).toBe(modalResult);

关于angularjs - 如何对 ui-bootstrap $uibModal 实例的结果进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43103677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com