AngularJS与链式承诺的业力测试

时间:2016-03-09 14:55:15

标签: javascript angularjs jasmine karma-runner

这是Controller中的功能:

angular.module("MyMod")
.controller("MyController", function(UserData, mtcLogService, $state,
    BroadcastService, $scope, $rootScope, ChartsService, PaxCountSummaryService) {

    self.waveCountSummary = function() {
        if (self.program.programID !== undefined) {
            PaxCountSummaryService.getWaveCountChartSummary(self.program.programID)
                .then(function(data) {
                    self.totalWaveCount = data[data.length - 1].count;
                    data.pop();
                    return (data || []).map(_.bind(ChartsService.tasksCountToChartData, this, _, "unknown"));
                })
                .then(function(chart) {
                    return self.replaceContentsOf(self.waveCountChartData, chart);
                });
        }
    };
});

这是我的工作测试:

fit("My test", inject(function ($rootScope, $controller, $q) {

    var results = [{
        pop: sinon.spy(),
        count: 1
    }];

    mockPaxCountSummaryService.getWaveCountChartSummary
        .returns($q.resolve(results));

    testController = $controller("PaxCountSummaryController", {
        $state: state,
        $scope: scope,
        $rootScope: $rootScope,
        PaxCountSummaryService: mockPaxCountSummaryService
    });

    testController.program = testProgram;
    testController.totalWaveCount = null;

    expect(testController.totalWaveCount).toBe(null);

    testController.waveCountSummary();
    scope.$apply();

    expect(testController.totalWaveCount).toBe(1);
}));

好的,这个测试有效。但是,如何在promise链中找到第二个THEN,以便测试是否调用了REPLACECONTENTSOF?

对此有何帮助?

1 个答案:

答案 0 :(得分:1)

嗯,这是我遇到多个问题的时候之一,但它确实按预期工作。我只需要为REPLACECONTENTSOF创建一个间谍。

这是最终的测试工作:

fit("MyTest.", inject(function($controller, $q) {

    var results = [{
        pop: sinon.spy(),
        count: 1
    }];

    mockPaxCountSummaryService.getWaveCountChartSummary
        .returns($q.resolve(results));

    testController = $controller("PaxCountSummaryController", {
        $state: state,
        $scope: scope,
        PaxCountSummaryService: mockPaxCountSummaryService
    });

    testController.program = testProgram;
    testController.replaceContentsOf = sinon.spy();
    testController.totalWaveCount = null;

    expect(testController.replaceContentsOf.callCount).toBe(0);

    testController.waveCountSummary();
    scope.$apply();

    expect(testController.totalWaveCount).toBe(1);
    expect(testController.replaceContentsOf.callCount).toBe(1);
}));