Sanket Patel
Sanket Patel

Reputation: 283

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!

Upvotes: 0

Views: 28

Answers (2)

adam-beck
adam-beck

Reputation: 6009

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

Upvotes: 1

kaeedo
kaeedo

Reputation: 458

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

Upvotes: 1

Related Questions