Hello, I recently started learning JS and encountered a problem while testing asynchronous methods with jasmine mocking.
Below is the code snippet I am trying to test:
test.factory('service', ['$http', '$q', function($http, $q) {
var _func = function(varB, successCallback, errorCallback) {
//Sanity check on input
if (isNaN(varB)) {
errorCallback('varB has to be a number');
return;
}
if (parseInt(varB) < 0) {
errorCallback('varB count has to be positive');
return;
}
$http.get('http://www.test.com').then(function(response) {
var data = angular.copy(response.data);
if (successCallback) {
successCallback(data);
}
}, function(errorResponse) {
if (errorCallback) {
errorCallback(errorResponse.data);
}
});
};
return {
func: function(varB) {
return $q(function(resolve, reject) {
_func(varB, resolve, reject);
});
}
};
}]);
One of the tests that I have written for this code snippet is as follows:
beforeEach(inject(function($injector) {
service = $injector.get(
'service');
$httpBackend = $injector.get('$httpBackend');
}));
it('should use the rejection handler if varB is in invalid format',
function() {
var successHandler = jasmine.createSpy('success');
var failHandler = jasmine.createSpy('fail');
service.func('abc').then(successHandler, failHandler);
expect(successHandler).not.toHaveBeenCalled();
expect(failHandler).toHaveBeenCalledWith('varB has to be a number');
}
);
However, I noticed that the line
expect(failHandler).toHaveBeenCalledWith('varB has to be a number');
never gets executed during the test. Even after adding debug statements in the service class, the mock was not detecting the callback being called with the specified argument.
If anyone has any insights or suggestions, I would greatly appreciate it! Thank you!