Search code examples
javascriptangularjsunit-testingkarma-jasmineangularjs-factory

AngularJS testing $resource - flush giving error


I have a factory

angular.module('RepServices', [ 'ngResource' ]).factory('Rep',
        function($resource) {
            return $resource('rep.do', {}, {
                get : {
                    method : 'GET',
                    params : {
                        action : "fetchRep"
                    },
                    isArray : false,
                    responseType : "text"
                }
            });
        });

and have created a test

describe('RepService test', function () {
    var httpBackend;
    var repService;
    var repResponseXML = '<RepEntity><active>false</active><repCode>C326</repCode></RepEntity>';

    beforeEach(module('rifApp'));

     beforeEach(inject(
         function ($injector) {
             httpBackend = $injector.get('$httpBackend');
             repService = $injector.get('Rep');// Rep is name of the factory
         })
     );

     describe('fetchRep', function () {
         it ('should call the RepServices to fetchRep', function () {
             var mockData = repResponseXML;
             var url = 'rep.do';

             httpBackend.expectGET(url).respond(mockData);

           var response =
             repService.get({repCode: 'C213', subfirm: '001'}, 
                     function(httpResponse) {console.log("httpResponse: " + httpResponse);}, 
                     function(httpErrorResponse) {});

             console.log(response);
             console.log("Promise: ");
             console.log(response.$promise);


             response.$promise.then(function() {console.log("callback");}, function() {console.log("errback");}, function() {console.log("progressback"); });


             httpBackend.flush()
         });

     });

});

Getting error when it calls flush (see error below). If I remove the flush then Karma reports success but it does not appear to be returning what I have called mockData

Error: [jqLite:nosel] Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element
http://errors.angularjs.org/1.2.21/jqLite/nosel
    at JQLite (C:/Users/D532335/Projects/Affirm/Trunk/RIFWeb/WebContent/javascript/lib/angular.js:2365)
.............

Solution

  • I ended up havinmg to include jquery whic the links from the error told me to do this. But I was still getting an error. Make sure you alwasy load the library dependencies in the same order as your app does.