我使用Angular-Bootstrap情态动词没有发现有像这样一个基本的控制器:嘲笑功能AngularUI模态控制器单元测试
.controller('DashboardHelpController', ['$scope', '$uibModal', function ($scope, $uibModal) {
var dhc = this;
dhc.open = function (size, resource) {
var modalInstance = $uibModal.open({
templateUrl: 'resourcePlayModal.html',
controller: 'ModalInstanceCtrl as mic',
size: size,
resolve: {
resource: function() {
return resource;
}
}
});
};
}])
它调用一个标准的模式实例控制器:
.controller('ModalInstanceCtrl', ['$uibModalInstance', 'resource', function ($uibModalInstance, resource) {
this.resource = resource;
this.cancel = function() {
$uibModalInstance.dismiss();
};
}])
而且这里是我的单元测试,模仿another SO post:
describe('Modal controller', function() {
var modalCtrl, scope, modalInstance;
beforeEach(module('MyApp'));
// initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
modalInstance = {
// create a mock object using spies
close: jasmine.createSpy('modalInstance.close'),
dismiss: jasmine.createSpy('modalInstance.dismiss'),
result: {
then: jasmine.createSpy('modalInstance.result.then')
}
};
modalCtrl = $controller('DashboardHelpController', {
$scope: scope,
$uibModalInstance: modalInstance
});
}));
it('should instantiate the mock controller', function() {
expect(modalCtrl).not.toBeUndefined();
});
it('should have called the modal dismiss function', function() {
scope.cancel;
expect(modalInstance.dismiss).toHaveBeenCalled();
});
});
T他的问题是,取消功能上没有找到范围:
Expected spy modalInstance.dismiss to have been called with [ 'cancel' ] but it was never called.
UPDATE:我本来试图调用cancel
作为一个功能:
it('should have called the modal dismiss function', function() {
scope.cancel();
expect(modalInstance.dismiss).toHaveBeenCalled();
});
这没有奏效。上面我的代码是解决原来的问题的尝试:有点
TypeError: scope.cancel is not a function
事情是复杂的,我的我使用Controller as
语法的,但这应该工作。谢谢你的帮助。
取消是一项功能。 'scope.cancel'不会调用它。即使你有括号,cancel()是ModalInstanceCtrl的一个函数,你永远不会在任何地方实例化,而不是$ scope的函数。 –
你是对的。请参阅我的更新。 'cancel()'是实例控制器的一个功能。我的问题在于我无法通过各种控制器和功能来跟踪范围。 – isherwood
不知道你为什么关心范围,因为没有2个控制器使用它。为什么在DashboardHelpController的测试中尝试测试cancel(),这是ModalInstanceCtrl的一个函数? –