0

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!

2 Answers 2

1

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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

I tried, its working!! thanks :) i will bug you for further questions if i get any , ok ?
1
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.