I have a test case that tests a service and have succeeded in checking if a get request is called in my test case :
var $httpBackend, Entry, Common;
beforeEach(module('contact_journal'));
beforeEach(inject(function($injector, _Entry_,_Common_,_$state_) {
$httpBackend = $injector.get('$httpBackend');
Entry = _Entry_;
Common = _Common_;
//$httpBackend.whenGET(URLS.entry_show_path+'?id=0').respond(200,{});
// this is required to stub ui-router cycle on $http request
state = _$state_;
spyOn(state,'go');
spyOn(state,'transitionTo');
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
describe('getEntry', function(){
it('should sent GET request', function() {
$httpBackend.expectGET(URLS.entry_show_path+'?id=0').respond(200,{});
var result = Entry.getEntry(0);
$httpBackend.flush();
console.log('After flush');
console.log(result);
expect(result).toEqual({});
});
});
Now I want the result variable to have the response of the service so that I can check the response code is 200. But as I have done the httpBackend flush afterwards I am unable to get the result after the success callBack executes instead the success gives me a promise. How do I get the result from my Entry.getEntry service call? Following is my service method :
entryService.getEntry = function(entry_id) {
show_page_loader();
return $http.get(URLS.entry_show_path, {params: { id: entry_id }})
.success(function(result){
console.log('In success');
console.log(result);
return result;
})
.error(function(data){
console.log('In error');
Common.common_flash_error_message();
console.log('error completed');
});
};
Thanks for any help.
Since the return value is a promise, you need handle it while unit testing. Here is how you can do it:
it('should sent GET request', function() {
$httpBackend.expectGET(URLS.entry_show_path+'?id=0').respond(200,{});
var result;
Entry.getEntry(0).then(function(data) {
result=data;
})
$httpBackend.flush();
console.log('After flush');
console.log(result);
expect(result).toEqual({});
});