gpt4 book ai didi

javascript - 如何模拟 uibmodal 的结果?

转载 作者:行者123 更新时间:2023-11-30 11:35:38 28 4
gpt4 key购买 nike

我有以下代码:

vm.data = [{name: 'test-1'},{name: 'test-2'}];

function addRecords(data) {
vm.data.push(data);
}

function openPopup() {

$uibModal.open({
templateUrl: 'modal-popup/modal-popup.html',
controller: 'ModalPopupController',
controllerAs: 'vm',
resolve: {
id: _.constant('123')
}
}).result.then(addRecords);
}

试图模拟这个,下面是声明:

let allData = [{name: 'test-1'},{name: 'test-2'}];
let data = {name: 'test-3'};

beforeEach(inject(function (_$q_, _$rootScope_, _$componentController_, _$uibModal_) {
$q = _$q_;
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
controller = _$componentController_;
$uibModal = _$uibModal_;

spyOn($uibModal, 'open').and.returnValue({
result: function() {
return $q.when(data);
}
});

vm = controller('bvcListings', {
$q,
data: allData,
$uibModal
});

$scope.$apply();
}));

describe('openPopup', function () {
it('should add records on modal results', function () {
vm.openPopup();
expect($uibModal.open).toHaveBeenCalled();
});
});

期望是,它应该添加:{name: 'test-3'} 作为现有数组的结果。

监视模态打开工作正常,但在获取结果后,它没有进入 addRecords 函数。我做错了什么?

检索到结果后需要在此处进行哪些更改才能进入回调函数。

最佳答案

.result.then 回调方法只有在调用modalInstance.close 方法时才会被调用,同时不要忘记传递data来自 close 方法,类似于 modalInstance.close(data)

在继续测试之前,您需要在 openPopup 函数中进行一项更改。它应该返回 $uibModal.open ,它基本上返回新创建的模态实例。此后,您可以轻松地控制模态以在需要时调用 dismiss/close 方法。

function openPopup() {
vm.modalInstance = $uibModal.open({
templateUrl: 'modal-popup/modal-popup.html',
controller: 'ModalPopupController',
controllerAs: 'vm',
resolve: {
id: _.constant('123')
}
});

vm.modalInstance.result.then(addRecords);
}

规范

$uibModal = _$uibModal_;
var data = {name: 'test-3'};
//creating fake modal which will help you to mock
var fakeModal = {
result: {
then: function(confirmCallback) {
//Store the callbacks
this.confirmCallBack = confirmCallback;
}
},
close: function( item ) {
//The user clicked OK on the modal dialog
this.result.confirmCallBack( item );
}
};
spyOn($uibModal, 'open').and.returnValue(fakeModal);

describe('It should data to vm.data when popup closed', function () {
it('should add records on modal results', function () {
vm.data = [{name: 'test-1'},{name: 'test-2'}];
let data = {name: 'test-3'};
vm.openPopup();
expect($uibModal.open).toHaveBeenCalled();
vm.modalInstance.close(data);
expect(vm.data.length).toBe(4);
expect(vm.data[3]).toBe(data);
});
});

Note: fakeModal has been referred from this post

关于javascript - 如何模拟 uibmodal 的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44569618/

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