我有一個函數返回一個有很多方法的對象,我需要檢查這個返回對象中的一個方法。我使用AngularJS和Karma + Jasmine作爲測試套件。如何在由函數返回的對象中調用方法?測試一個函數返回的對象的方法
function modalOptions() {
.........
return this.$q((resolve) => {
// test accessable here
this.solveModel = {
save:() => {
// test can't call save()
this.saveToDB = this.toSendToDB;
},
cancel:() => { ...
},
delete:() => { ...
}
};
});
}
我的測試有點像這樣...
it('should save modal with the data', function() {
scope.$apply();
expect(vm.modalOptions).toBeDefined();
vm.toSendToDB = true; // hard-coded
vm.savedToDB = undefined // default value from other controller
spyOn(vm, 'modalOptions').and.callThrough();
console.log(vm.modalOptions()); // gives weird response: c{$$state: Object{status: 0}} instead of the solveModal object
expect(vm.toSendToDB).toBeTruthy();
expect(vm.savedToDB).toBeTruthy();
});
難道你不需要像'vm.modalOptions()。then(function(value){console.log(value);})'得到solveModal對象嗎?因爲它返回一個承諾不? – Matthias
實際上這是我正在做的事情,但測試並沒有進入當時的通話。後來,我只是保持手動調用功能,它的工作。奇怪,但工作:) – Jamie