Javascript 角度测试-承诺不返回数据

Javascript 角度测试-承诺不返回数据,javascript,angularjs,testing,jasmine,karma-runner,Javascript,Angularjs,Testing,Jasmine,Karma Runner,我不明白为什么我的HomeCtrl中的vm.chartData永远不会填充我在beforeach()中模拟的数据。log(scope.vm.chartData)返回undefined,即使其他范围变量(如graphLoading)已正确定义和更改 describe('HomeCtrl', function () { var controller, scope, myService, q, $timeout; beforeEach(module('dashboardApp'));

我不明白为什么我的HomeCtrl中的vm.chartData永远不会填充我在beforeach()中模拟的数据。log(scope.vm.chartData)返回undefined,即使其他范围变量(如graphLoading)已正确定义和更改

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);
        });
    });
});
来自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);
};
这是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);
            });

您的控制器代码正在
图表返回的承诺内的对象中查找
数据
属性。获取

vm.chartData = chart.data;
但是测试的存根返回的对象没有
数据
属性:

myService.get.and.returnValue(q.when({
    result: 'Stuff'
}));

因此,
vm.chartData
被指定为未定义。

您是否尝试过先解决超时问题,然后再解决scope.digest?不要转储所有代码,让人们查看每一行以查找实际错误。您可以先执行console.log并检测可能存在的嵌套问题。它为其他人解决您的问题节省了很多时间。我尝试将超时时间替换为摘要,但没有效果。syarul,我只是展示一个测试用例以及控制器和工厂类的相关部分。您可以看到Chart.get返回一个承诺,vm.chartData在承诺返回后填充,等等。我假设我遗漏了一些明显与jasmine有关的内容,很抱歉打扰您。实际代码是否与单元测试有相同的问题?不,代码运行良好