我寫了一個組件,它發佈了某些服務的數據。 我無法在單元測試中涵蓋此功能。如何輸入測試`然後'功能?如何進行單元測試。然後使用jamsine功能
angular.module('myapp')
.component('performAnalysis', {
templateUrl: 'analysis.component.html',
controller: PerformAnalysisController,
controllerAs: 'vm'
});
function PerformAnalysisController(UnitySizerService, SizingService, MarshallDTO, CommonService) {
let vm = this;
vm.$onInit = $onInit;
function $onInit() {
let unitySizerDTO = MarshallDTO.generateDTO();
let previousDTO = CommonService.getProperty('previousDTO');
vm.dataChanged = JSON.stringify(unitySizerDTO) === JSON.stringify(previousDTO);
/* Call Backend API only if DTO is changed */
if (!vm.dataChanged) {
/* Loader On */
vm.activateLoader = true;
SizingService.postSizingResults(unitySizerDTO).then(function (data) {
UnitySizerService.resultSummary = data;
/* New Data coming from Backend */
vm.dataChanged = true;
/* Loader Off */
vm.activateLoader = false;
CommonService.setProperty('previousDTO', unitySizerDTO);
vm.unitySizerService = UnitySizerService;
});
}
else {
vm.unitySizerService = UnitySizerService;
}
}
}
這是我寫的,但我不能夠覆蓋這裏面then
功能測試文件:
describe('my Component', function() {
beforeEach(module('myApp'));
let vm;
let $rootScope;
let $componentController;
let UnitySizerService, SizingService;
beforeEach(inject(function (_$componentController_, _$rootScope_, _UnitySizerService_, _SizingService_) {
$componentController = _$componentController_;
$rootScope = _$rootScope_;
UnitySizerService = _UnitySizerService_;
SizingService = _SizingService_;
vm = $componentController('performAnalysis');
}));
it('should be defined', function() {
expect(vm).toBeDefined();
expect(vm.$onInit).toBeDefined();
expect(UnitySizerService).toBeDefined();
});
it('should show loader', function() {
vm.$onInit();
vm.dataChanged = false;
expect(vm.activateLoader).toBeTruthy();
});
});
是不是很簡單提取傳入'.then'的功能,只是自行測試嗎?所以你會得到像'then thenhandler(data){...}'定義的東西,它被用作'.then(thenHandler)',並且可以單獨測試'expect(thenHandler(testData),toBe(expectedResult) '等等 – vlaz