我的代码是:
$scope.openModal = openModal;
function openModal(data){
var info = data || {}
ModalService.showModal({
templateUrl: ENVApp+"/myview.html",
controller: "ModalController",
inputs: {
icon : "",
title: "Additional",
data : info
}
}).then(function (modal) {
modal.element.modal();
modal.close.then(function (res) {
if(res.data != 'cancel'){
if(!res.data.id){
create(res)
}else{
update(res)
}
}
});
});
}
用Karma测试这个的正确方法是什么?这是我到目前为止所做的:
在beforeEach
:
this.ModalService = {
showModal: function(obj) {
var deferred = $q.defer();
deferred.resolve({
element: {
modal: jasmine.createSpy(),
close: function() {
var deferred2 = $q.defer();
return deferred2.promise;
}
}
});
return deferred.promise;
}
};
this.UserService = {
user: {
id: 2
},
updateCategory: function(data, type) {
var deferred = $q.defer();
deferred.resolve({
data: {
rows: 'response'
}
});
return deferred.promise;
}
}
this.controller = $controller('ProfileAdditionalController', {
'$scope': this.scope,
'$rootScope': this.rootScope,
'$state': this.state,
"$stateParams": this.stateParams,
'ModalService': this.ModalService,
'UserService': this.UserService,
'ResourceService': this.ResourceService,
'$upload': this.upload,
'userData': this.userData
});
对于我的实际测试:
it('should open a modal when requested', function() {
this.scope.openModal();
expect(this.ModalService.showModal)
});
但这并没有多大意义。想法?
答案 0 :(得分:1)
要测试控制器上的openModal
功能,基本上您要验证以下内容(3次测试)
ModalService.showModal
进行调用then
函数是否正在执行其想要执行的操作then
函数是否正在执行其想要执行的操作首先,您可能需要在ModelService.showModal上设置间谍(模拟):
spyOn(ModalService, 'showModal).and.returnValue($q.when(mockModal))
现在,在您的测试中,您将触发该功能和$ scope。$ digest call:
$scope.openModal(data);
$scope.$digest() // to propagate the `resolve()` result of the promise)
这将触发第一个then
回调,(将mockModal作为参数传递),然后您可以验证其行为。
与验证第二个回调类似,您需要模拟已解析的modal
对象。