0
我想寫一個角度控制器的單元測試,其中變量從服務調用中分配值。使用角度服務的角度控制器的單元測試
我可以找出方式,直到它的JSON調用,但是當我嘗試調用API時,我得到錯誤。我不知道如何讓我的服務調用映射到測試。
控制器
var vm = this;
vm.creationDate = 8; // test passed
vm.mainServiceNumber = MainService.getNumber();// test passed
vm.addNumberFunction = function(a, b){// test passed
vm.sumOfTwoNumbers = MainService.addNumbers(a, b);
}
MainService.getNumberFromJson().then(function(response){// test failed
vm.numberFromJson = response;
})
var id =10;
vm.getNumberFunction = function(id){// test failed
MainService.getNumberJsonFunction(id).then(function(response){
vm.numberFromJsonFunction = response;
})
}
服務
var service = this;
service.getNumber = function(){
return 8;
}
service.addNumbers = function(a, b){
return a+b;
}
service.getNumberFromJson = function(){
var num = {};
num = $q.defer();
num.resolve(7);
return num.promise;
}
service.getNumberJsonFunction = function(id){
var deferred = {};
deferred = $q.defer();
deferred.resolve(10);
return deferred.promise;
}
測試用例
var vm;
var MainService;
beforeEach(module('myApp'));
beforeEach(inject(function(_$controller_, _MainService_) {
vm = _$controller_('MainController');
MainService = _MainService_;
}));
/*it('should have a timestamp creation date', function() {
expect(vm.creationDate).toEqual(jasmine.any(Number));
});*/
it('should have a value', function() {
expect(vm.creationDate).toEqual(8);
});
it('should get a value from service', function() {
expect(vm.mainServiceNumber).toEqual(8);
});
it('should get a value from service after addition', function() {
vm.addNumberFunction(3, 3);
expect(vm.sumOfTwoNumbers).toEqual(6);
});
it('should get a value from service after a service call without passing params', function() { //Test Failed
expect(vm.numberFromJson).toEqual(7); //Expected undefined to equal 7.
});
it('should get a value from service after a service call passing params', function() {// Test Failed
vm.getNumberFunction(10)
expect(vm.numberFromJsonFunction).toEqual(10);//Expected undefined to equal 10.
});
我已經刪除了我的所有測試代碼像spyon,$ http保持代碼簡單&乾淨。
我使用https://github.com/Swiip/generator-gulp-angular對角項目的基本設置