如何使用sinon存根来替换promise,以便响应被模拟?

时间:2016-03-22 20:46:17

标签: javascript angularjs unit-testing jasmine

我希望整个承诺都存在。

我正在使用带有javascript和jasemine和karma的角度js版本1。

这是我的代码:

appcontrolmod.controller('loginCtrl', ['$rootScope', '$scope', 'personService', 
    function ($rootScope, $scope personService) {   

    $scope.getUser= function(){

        //I want to stub this to return an expected response?
        personService.getUser().then((response) => {

                //I want to stub the response of this promise?
                console.log(response);

                if(response){
                    //update model
                }else{
                    //show error message
                }

        });

    }

    $scope.getUser();
}]);

提前致谢!

1 个答案:

答案 0 :(得分:1)

我会说那个地方监视方法,只是从那个间谍那里返回一些假数据

//place spy over it & return fakedata, it should be in global before each
var getUserSpy = spyOn(personService, 'getUser').and.callFake(function() {
  return {
    then: function(callback) { return callback({Id: 1, Name: 'Something'}); }
  };
});

it('should show success when modal login returns success response', function() {
    scope.getUser();
    //do assert by calling expect statement
    expect(personService.getUser).toHaveBeenCalled();
    expect(scope.user.Id).toBe(1); //assuming scope.user has filled with response user data
});