how to test and resolve Controller data (.then fun

2020-02-02 03:28发布

    I am testing a controller that uses a service that returns a promise. I need to resolve promise. I am using Jasmine 2. 

    Here is Spec code

      beforeEach(inject(function ($controller, $rootScope, _myService_, _$q_, _$rootScope_, _$httpBackend_, $http) {


         scope = $rootScope.$new();
         $q = _$q_;
         $httpBackend = _$httpBackend_;
         $rootScope = _$rootScope_;
         myService = _myService_;
$http = $http;
         ctrl =  $controller('Ctrl', { '$scope': scope, 'myService': myService });
     spyOn(myService, "getDateRangeData").and.callThrough();

      }));


        it('getDateRangeData return Data obj', function() {

    myService.getDateRangeData().then(function(response) {
      console.log('Success', response);
    }); 
        scope.$digest()      

      });

service js
function getDateRangeData(obj) {
  return $http({
    method: 'POST',
    url: 'https:URL',
     headers: {
       'Content-Type': 'application/json',
       'X-Auth-Token': self.token
     },
    data: obj
  })
}

console not returning any obj.Shows error.Unexpected request: POST https:URL No more request expected. i need data from Ctrl . In Crtl I am getting data but not in testcase. deferred. how to get Api data. Api data is object. or there is another aprroch to get Ctrl return promise to resolve and getData? added sevice js code where request send.

can anyone help soon please.

2条回答
时光不老,我们不散
2楼-- · 2020-02-02 04:07

First of all you are "spying on" the wrong method. We use spyOn for two reasons:

  • To expect(method).toHaveBeenCalled
  • To mock the return value

In your case the spyOn does not achieve any of these two.

You should spyOn the $http instead. Since the actual http call is not required for your test, the reason being: the objective is not to test $http.

this.$http = $http;
spyOn(this, '$http').and.callFake(function(args) {
    return {
        then: function(fn) {
            return fn('response');
        }
    };
});

And in it block:

it('getDateRangeData return Data obj', function() {
    myService.getDateRangeData('test')
    .then(function(response) {
        console.log('Success', response);
        expect(response).toEqual('response');
    });
    expect(this.$http).toHaveBeenCalledOnceWith('test');   
});
查看更多
再贱就再见
3楼-- · 2020-02-02 04:13

If you want the spyOn to actually use the correct implementation instead of the mock you can use callThrough() instead of callFake().

Try it like this:

spyOn(myService, "getDateRangeData").and.callThrough();
查看更多
登录 后发表回答