I'm currently working on writing a code to test the service call in my controller. The goal is to unit test a specific function within the controller that makes the service call and retrieves data. While I am using local JSON for testing purposes, the actual service call will be made eventually.
As I delved into unit testing, I learned that I need to create a spy object. However, I encountered an error stating "TypeError: jasmine.CreateSpyObj is not a function." Being new to unit testing, I am struggling to create a spy object and progress further with my testing. Below is my code, requesting assistance to resolve this issue.
Furthermore, once I successfully create the spy object, I am uncertain about the next steps. My aim is to verify if the service call is successful and if I receive a response from the service.
Any help would be greatly appreciated as I have been facing challenges with this for several days now.
Service Code:
//app is the module name
app.factory('appServices', ['$rootScope', '$http', function($rootScope, $http) {
var appServices = {};
appServices.getData = function(){
return $http.get('scripts/services/data/unitTesting.json');
};
unitTesting.json Code:
{
"name":"unit testing",
"countryCode": "EG",
"countryName": "Egypt",
"region": "Africa"
}
Controller Code:
getData: function(){
appServices.getData().then(function(response) {
if (response && response.data) {
$scope.testVariable= response.data.name;
}
});
},
Unit Test Code:
describe('myCtrl', function() {
beforeEach(module('app'));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('service call test', function() {
var $http,$httpBackend,appServices,
myService,$q,$rootScope,controller;
var mockItem =
{
"name":"unit testing",
"countryCode": "EG",
"countryName": "Egypt",
"region": "Africa"
}
beforeEach(inject(function(_$http_,_$httpBackend_,appServices,_$q_,
_$rootScope_) {
$http = _$http_;
$httpBackend = _$httpBackend_;
appServices = appServices;
$rootScope = _$rootScope_;
$q =$q_;
spyOn(appServices, 'getData').and.returnValue($q.when(mockItem));
controller = $controller('myCtrl', { $scope: $scope });
}));
it('Service call test ', function() {
controller = $controller('myCtrl', { $scope: $rootScope.new() });
controller.getData();
expect(appServices.getData).toHaveBeenCalled();
});
});
});
ERROR :
TypeError: jasmine.spyOn is not a function