Skip to content Skip to sidebar Skip to footer

Testing A Service That Requires $resource Using $httpBackend In Angular.JS

I've looked at several answers on SO, and have read through the official docs. From what I've seen, this should be working. In my service, I have: var RESTServices = angular.module

Solution 1:

After trying many things, and doing some more research, it seems to be that the module that includes the declaration of 'ngResource' needs to be included in the test for it to work. For example, I declared 'ngResource' in app.js in the module myApp, so once I include this, the tests work.

in app.js:

var myApp = angular.module('myApp', [
  'ngRoute',
  'ngCookies',
  'ngResource',
  'myControllers',
  'myDirectives',
  'myServices',
  'RESTServices'
]);

in the spec:

describe('Testing Services that require API calls', function() {

    var restCall,
        $httpBackend,
        $resource,
        scope;

    beforeEach(function () {

        module('myApp'); //this line fixed it
        module('RESTServices');

        inject(function (_$httpBackend_, _restCall_, _$resource_) {
            $httpBackend = _$httpBackend_;
            $resource = _$resource_;
            restCall = _restCall_;
        });

        scope = {};

    });

    describe('servList', function() {
        it('Should supply a list of servers', function () {
            var serverList = ['Thufir Hawat', 'Duncan Idaho'];
            $httpBackend.expectGET('http://localhost:1000/apiv1/servers')
                .respond({server_list: serverList});
            restCall.servList({}, scope);
            $httpBackend.flush();
            expect(arraysEqual(scope.servers, serverList)).toBeTruthy();
        });
    });
});

ETA: Someone else chimed in that they fixed this problem for themselves by adding module('ngResource'); where I added module('RESTServices');. I'm willing to bet that the important thing is having a ngResource imported into your tests, either directly or indirectly.


Post a Comment for "Testing A Service That Requires $resource Using $httpBackend In Angular.JS"