Unit-testing nested services with Jasmine 2.3.4 in AngularJS 1.4.6

127 views
Skip to first unread message

Krizzo

unread,
Sep 24, 2015, 6:32:17 PM9/24/15
to Jasmine
I have problems to test services of the app because I don't know how to do it.
In google search results I've found many tutorials and examples but nothing was useful for my purpose.

Also, I don't know when to use the $httpBackend and why I need to define a fake service?!

However my intention is to test the services whether they're return a response or not as well as you define an item and make a GET request to see if the value exists and so on.
But the main issue is to understand how can I define a unit test for services in my examples.

To have a better imagine, I put the code in this post:

Firstly testing the CRUDService:
angular.module('testApp')
   
.factory('CrudService', ['ResService',
       
function (ResService) {
           
var service = {
                getAllCompanies
: getAllCompanies,
                getAllGroups
: getAllGroups
           
};

           
return service;

           
function getAllCompanies() {
               
return ResService.company.query();
           
}
           
           
function getAllGroups() {
               
return ResService.group.query();
           
}
   
}]);

Following the Service who communicates with the backend: ResService:
angular.module('testApp')
   
.factory('ResService', ['$resource', 'baseUrl',
       
function ($resource, baseUrl) {
           
return {

               company
: $resource(baseUrl + '/api/company/:Id/:code', {
                   
Id: '@Id',
                    code
: '@code'
               
}, {
                   
'update': {
                        method
: 'PUT'
                   
}
               
}),

               
group: $resource(baseUrl + '/api/group/:Id', {
                   
Id: '@Id'
               
}, {})
...

Do anyone have an idea? I've tried this example to integrate in my test but it was not the correct way..

Luke Winikates

unread,
Sep 26, 2015, 9:32:16 PM9/26/15
to Jasmine
Hi Krizzo,

I'd refer to the Angular docs to get a sense of Google's suggested strategy for testing Angular code that makes http requests: https://docs.angularjs.org/api/ngMock/service/$httpBackend

If that doc doesn't get you past the current hurdle, you may find it useful to track down a google group related to Angular, or to ask your question on StackOverflow. Test code for Angular uses a lot of Angular-specific patterns. Those aren't part of Jasmine itself, so the best place to find expertise on your specific situation is probably within the Angular community.

Hope that helps.
Reply all
Reply to author
Forward
0 new messages