![](/img/trans.png)
[英]How to test .then(function in Unit Testing AgularJS with jasmine
[英]How to unit test $uibModal in Jasmine? (unit testing injected library)
所以我从引导程序中使用$ uibModal,并且在AngularJS控制器中有以下代码:
vm.openPopup = function() {
$uibModal.open({
templateUrl: 'popup.html',
controller: function() {
var modal = this;
modal.hi = function() {
// some code here
}
}
});
};
如何在Jasmine中调用modal.hi函数并对其进行单元测试以确保其正常工作?
因此,与测试这个代码的主要问题是:你基本上是“埋”匿名函数( modal.hi
) 另一个匿名函数(内$uibModal.open
)。 这使得测试非常棘手。
您有一些选择:a。)您可以模拟$uibModal
服务,b。)您可以重组代码,或c。)您可以将hi
函数放到vm
本身,然后从您的vm
调用它测试。 我认为最后一种选择是最方便的选择,但是以下是这三种方法的一些示例。
$uibModal
服务 describe('Test vm.openPopup', function () {
var mockUibModal = {
open: function(options){
var ctrl = options.controller();
// call your `hi` function:
ctrl.hi();
}
};
beforeEach(function(){
module(function($provide){
$provide.value('$uibModal', mockUibModal);
});
});
});
从那里,您可以调用vm.openPopup
方法,然后测试结果。 请注意, module
功能来自angular-mocks ,您需要在测试中安装/随附。 相关问题:“ 使用茉莉花进行单元测试时,如何在AngularJS中模拟服务? ”
这是我经常使用的一种模式,其中涉及将您要测试的逻辑/功能转移到一个单独的工厂中:
var app = angular.controller('YourController', function ($uibModal, MyHelperFactory) {
var vm = this;
var modal;
var helper = MyHelperFactory(vm, modal);
vm.openPopup = function () {
$uibModal.open({
templateUrl: 'popup.html',
controller: function () {
modal = this;
modal.hi = helper.hi;
}
});
};
});
app.factory('MyHelperFactory', function () {
return function (vm, modal) {
return {
hi: function () {
// some code here, maybe it needs to reference the `vm` object, whatever...
}
}
};
})
这种方法的好处是,您可以自己测试MyHelperFactory
,而无需实例化YourController
,而无需涉及$uibModal
服务。 通常,这是我最喜欢的方法:没有内联/匿名函数-将这种逻辑放入帮助程序工厂,并从我的控制器中删除。
hi
函数放到vm
var app = angular.controller('YourController', function ($uibModal, MyHelperFactory) {
var vm = this;
// this pattern allows your function to be scoped with the not-yet-existing `modal` object
vm.hi = function (modal) {
return function () {
// some code here
}
};
vm.openPopup = function () {
$uibModal.open({
templateUrl: 'popup.html',
controller: function () {
var modal = this;
modal.hi = vm.hi(modal);
}
});
};
});
从那里,您可以在测试中通过调用vm.hi
进行测试。 我将此方法称为“肮脏”,因为它向vm
对象添加了hi
方法,并且通常避免向vm
对象添加控制器范围内实际上不需要的任何属性。 但是在这种情况下,我们违反了该规则,因为这是“暴露”您要测试的功能的最快/最简单的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.