[英]Angular Testing - promise not returning data
I can't see why vm.chartData in my HomeCtrl never gets populated with the data i've mocked to it in the beforeEach(). 我看不到为什么HomeCtrl中的vm.chartData永远不会填充之前在beforeEach()中嘲笑的数据。 the console.log(scope.vm.chartData) returns undefined even while the other scope vars like graphLoading are defined and changed properly. 即使已定义并正确更改了诸如graphLoading之类的其他作用域变量,console.log(scope.vm.chartData)仍返回未定义。
describe('HomeCtrl', function () {
var controller, scope, myService, q, $timeout;
beforeEach(module('dashboardApp'));
beforeEach(inject(function ($controller, $rootScope, $q, _$timeout_) {
controller = $controller;
scope = $rootScope.$new();
$timeout = _$timeout_;
myService = jasmine.createSpyObj('Chart', ['get']);
q = $q;
}));
describe('when returning promises', function () {
beforeEach(function () {
myService.get.and.returnValue(q.when( { result:
'Stuff'
}));
controller('HomeCtrl as vm', { $scope: scope, Chart: myService });
scope.$apply();
});
it('test dirty graph init', function () {
expect(scope.vm.graphLoading).toBe(true);
scope.vm.dirtyTestGraph();
scope.$digest();
$timeout.flush();
expect(scope.vm.graphLoading).toBe(false);
console.log(scope.vm.chartData);
});
});
});
relevent code from homectrl 来自homectrl的相关事件代码
vm.dirtyTestGraph = function() {
vm.graphTitle = 'Deposit Amount';
$timeout(function(){
Chart.get( { interval:'3h', type:'_type:deposit',
from:1416960000000, to:Date.now() } )
.then(function(chart){
vm.graphLoading = false;
vm.chartData = chart.data;
});
}, 2000);
};
and here is the return value of Chart.get in the Chart factory 这是Chart工厂中Chart.get的返回值
return $q.all([chartData])
.then(function(data){
var graphData = data[0].data.facets[0].entries;
var newData = [];
graphData.forEach(function(element){
var newElem = {
time: element.time,
deposits: element.total.toFixed(2)
};
newData.push(newElem);
});
return new Chart(newData);
});
Your controller code is looking for a data
property in the object within the promise returned by Chart.get
: 您的控制器代码正在Chart.get
返回的Chart.get
寻找对象中的data
属性:
vm.chartData = chart.data;
But your test's stub is returning an object without a data
property: 但是您的测试存根正在返回没有data
属性的对象:
myService.get.and.returnValue(q.when({
result: 'Stuff'
}));
So vm.chartData
gets assigned with undefined. 因此, vm.chartData
被分配了未定义的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.