gpt4 book ai didi

javascript - 如何对 Angular-UI Bootstrap Modal 组件的 'resolve' 属性进行单元测试

转载 作者:数据小太阳 更新时间:2023-10-29 04:44:14 26 4
gpt4 key购买 nike

我正在尝试编写一个单元测试,断言正确的变量正在从 Angular-UI Bootstrap 发送到 ui.bootstrap.modalresolve 属性组件。这是我目前所拥有的:

// Controller
angular.module('app')
.controller('WorkflowListCtrl', function ($scope, $modal) {
// Setup the edit callback to open a modal
$scope.edit = function(name) {
var modalInstance = $modal.open({
templateUrl: 'partials/editWorkflowModal.html',
controller: 'WorkflowEditCtrl',
scope: $scope,
resolve: {
name: function() { return name; }
}
});
};
});

值得注意的是 resolve.name 属性必须是 Angular-UI 组件才能正常工作的函数 - 之前我曾尝试过 resolve: { name: name } 但这没有用。

// Unit Test
describe('Controller: WorkflowListCtrl', function () {

// load the controller's module
beforeEach(module('app'));

var workflowListCtrl,
scope,
modal;

// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {

scope = $rootScope.$new();
modal = {
open: jasmine.createSpy()
};

workflowListCtrl = $controller('WorkflowListCtrl', {
$scope: scope,
$modal: modal
});

it('should allow a workflow to be edited', function() {
// Edit workflow happens in a modal.
scope.edit('Barney Rubble');
expect(modal.open).toHaveBeenCalledWith({
templateUrl: 'partials/editWorkflowModal.html',
controller: 'WorkflowEditCtrl',
scope: scope,
resolve: {
name: jasmine.any(Function)
}
});
});
}));
});

目前,这只是检查 resolve.name 属性是一个函数,但我真正想做的是断言 resolve.name函数返回 Barney Rubble。这种语法显然不起作用:

expect(modal.open).toHaveBeenCalledWith({
templateUrl: 'partials/editWorkflowModal.html',
controller: 'WorkflowEditCtrl',
scope: scope,
resolve: {
name: function() { return 'Barney Rubble'; }
}
});

似乎我想以某种方式监视 resolve.name 函数以检查它是用 Barney Rubble 调用的,但我想不出办法那。有什么想法吗?

最佳答案

所以我想出了一个办法来做到这一点。

$scope 上定义一个“私有(private)”函数:

$scope._resolve = function(item) {
return function() {
return item;
};
};

修改原来的$scope函数来调用这个“私有(private)”方法:

$scope.edit = function(name) {
var modalInstance = $modal.open({
templateUrl: 'partials/modal.html',
controller: 'ModalCtrl',
scope: $scope,
resolve: {
name: $scope._resolve(name)
}
});
};

更新您的测试以模拟此函数并返回原始值,然后您可以测试它是否已正确传递。

it('should allow a workflow to be edited', function() {
// Mock out the resolve fn and return our item
spyOn($scope, '_resolve').and.callFake(function(item) {
return item;
});

// Edit workflow happens in a modal.
scope.edit('Barney Rubble');
expect(modal.open).toHaveBeenCalledWith({
templateUrl: 'partials/modal.html',
controller: 'ModalCtrl',
scope: scope,
resolve: {
name: 'Barney Rubble'
}
});
});

关于javascript - 如何对 Angular-UI Bootstrap Modal 组件的 'resolve' 属性进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23128769/

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