将服务模拟到控制器中

时间:2015-03-11 20:46:09

标签: javascript angularjs testing jasmine karma-jasmine

我试图使用Jasmine 2.2.0模拟服务:CheckoutService.patch()将一个承诺返回到我的CheckoutController

describe('CheckoutController', function() {
    var $scope, vm, checkoutServiceMock, def;

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

        checkoutServiceMock = jasmine.createSpyObj('CheckoutService', ['patch']);

        inject(function($rootScope, $controller, $q){
            def = $q.defer();

            $scope = $rootScope.$new();

            vm = $controller('CheckoutController', {
                $scope: $scope,
                CheckoutService: checkoutServiceMock
            });

            checkoutServiceMock.patch.andReturn(def.promise);
        });
   });
});

但我得到了:TypeError: 'undefined' is not a function (evaluating 'checkoutServiceMock.patch.andReturn(def.promise)')

我缺少什么?

1 个答案:

答案 0 :(得分:2)

我想您应该将andReturn更改为and.callfake(),例如:

spyOn(checkoutServiceMock, "patch").and.callFake(function() {
  return def.promise;
});

有关Jasmine 2.2的信息,请参阅docs