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.
First of all you are "spying on" the wrong method. We use
spyOn
for two reasons:expect(method).toHaveBeenCalled
return value
In your case the
spyOn
does not achieve any of these two.You should
spyOn
the$http
instead. Since the actual http call is not required for your test, the reason being: the objective is not to test$http
.And in
it
block:If you want the spyOn to actually use the correct implementation instead of the mock you can use
callThrough()
instead ofcallFake()
.Try it like this: