简体   繁体   中英

Unit Testing promise in service in angular js

i am trying to unit test the below function :

  Service.test = function(id) { return this.getDetails(id).then(function (details){ return "name"; }); }; 

So far i have tried it by myself and done the following thing:

 describe( 'TempServ', function() { var TempSer, $httpBackend, $q, CapabilityService; beforeEach(inject(function(_TempServ_, _$httpBackend_, _$q_, _CapabilityService_) { TempServ = _TempServ_; $q = _$q_; $httpBackend = _$httpBackend_; CapabilityService = _CapabilityService_; })); it(" should be in Pending state",function() { spyOn(TemplateService, 'getDetails').and.callThrough(); console.log(TemplateService.test()); }); }); 

I want something, that can mock the getDetails and i can return what i want instead what really would be returned and test function to work by itself fully . Only the getDetails to be mocked!

spyOn(TemplateService, 'getDetails').and.callThrough();

This line will execute the actual implementation of getDetails in a spy context. You can use something like

spyOn(TemplateService, 'getDetails').and.returnValue(true)

instead. If you want to test what happens inside the callback, usually you need to manually trigger a digest cycle update via $scope.$apply();

Try doing something like this

spyOn(TemplateService, 'getDetails').and.returnValue($q.when('mockDetails'));
$rootScope.$digest();

This will allow you to make a test like the following:

it('should be in pending state', function(done) {
  spyOn(TemplateService, 'getDetails').and.returnValue($q.when('mockDetails'));


  TemplateService.test().then(function(result) {
    expect(result).toBe('name'); // this could also be a value computed with "mockDetails"
    done();
  });

  $rootScope.$digest();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM