如何使用Karma对承诺链进行单元测试?

时间:2015-05-08 14:04:56

标签: javascript promise karma-runner

我的控制器代码有:

        save: function () {
            var that = this;
            patientCache.saveCurrentPatient().then(function(){
                return adherenceCache.updateAdherenceSchedule(that.model.patientId)
            }).then(function () {
                that.buildAdherenceUrl();
            });
        },

我想测试patientCache.saveCurrentPatient()adherenceCache.updateAdherenceSchedulethat.buildAdherenceUrl被调用。

这是我的测试:

beforeEach(function() {
  module('mapApp');

  return inject(function($injector) {
    var $controller, $rootScope;
    $rootScope = $injector.get('$rootScope');
    $controller = $injector.get('$controller');

    scope = $rootScope.$new()
    $modalMock = jasmine.createSpyObj('$modal', ['open']);
    adherenceCacheMock = jasmine.createSpyObj('adherenceCache', ['getAdherenceSchedule']);
    patientCacheMock = jasmine.createSpyObj('patientCache', ['saveCurrentPatient']);

    $controller('PatientAdherenceController', {
        $scope: scope,
        $modal: $modalMock,
        adherenceCache: adherenceCacheMock,
        patientCache: patientCacheMock
    });
    return scope.$digest();

  });
});


fit('should save the patient and update the adherence schedule on save', function() {
    scope.save();

    expect(patientCacheMock.saveCurrentPatient).toHaveBeenCalled();
});

然而,我收到错误:

TypeError: 'undefined' is not an object (evaluating 'patientCache.model.currentPatient')

1 个答案:

答案 0 :(得分:1)

也许我错过了一些东西,但jasmine.createSpyObj创造了新的间谍,没有附加任何实施。你想要的是一个调用原始函数的间谍,因为你的承诺链假定存在patientCache.saveCurrentPatient。尝试使用spyOn(obj, 'patientCache').and.callThrough()语法设置间谍。请注意,为了执行此操作,您需要嵌入方法以在对象obj中进行测试:

var obj = {
  patientCache: patientCache // where patientCache is the actual service
}

当然,如果你想嘲笑这些服务,你可以注入附加了伪实现的间谍......使用Jasmine的and.returnValueand.callFake

相关问题