Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
697 views
in Technique[技术] by (71.8m points)

angularjs - how to test and resolve Controller data (.then function()) promise and get orginal Data in Jasmine2

    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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...