1

I am trying to write a unit test for an AngularJS service that uses $http and $q. I have done this without issue in the past and even have unit tests that work. Reading through all of the post here in SO, none of them seem to address my specific situation, which is that I am trying to test a service, not a controller.

After many different attempts to fix this issue I still get the No pending request to flush error. I have confirmed, as best I could, that $http is being called.

Here is all of the code as it stands now, after trying various approaches found here on SO, and the AngularJS documentation.

I would like to point out that the service works live, just not when using Karma and Jasmine.

Service

(function(angular, undefined){
    "use strict";

    angular.module('module.http',[])
        .service("noHTTP",['$q', '$http', function($q, $http){

            this.configure = function(){
                angular.noop();
            }

            this.createTransport = function(){
                return new noREST();
            }

            function noREST(){
                var SELF = this;

                this.create = function(resourceURI, formdata){
                    var json = angular.toJson(formdata);

                    var deferred = $q.defer(),
                        req = {
                            method: "POST",
                            url: resourceURI,
                            data: json,
                            headers: {
                                "Content-Type": "application/json",
                                "Accept": "application/json"
                            },
                            withCredentials: true
                        };

                    $http(req)
                        .success(function(data){
                            console.log(angular.toJson(data) );

                            deferred.resolve(data.d);
                        })
                        .error(function(reason){
                            console.error(reason);
                            deferred.reject(reason);
                        });



                    return deferred.promise;
                }
            }

        }])
    ;
})(angular)

Test Data

var CRUD = {
    POST: {
        request: {
            url: "http://img.local/NoCacheManifest",
            data: {
              "TableName":"Addresses","EntityName":"Address","Count":60,"LastTransaction":"2015-03-23T13:50:52.16","Query":null,"StorageLocation":"indexedDB","IndexedDB":"{\"keys\": \"++\", \"pk\":\"AddressID\"}"
            },
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json"
            }
        },
        response: {
            "odata.metadata": "http://img.local/odata/$metadata#NoCacheManifest/@Element",
            "ID": 91,
            "TableName": "Test",
            "EntityName": "Test",
            "Count": 60,
            "LastTransaction": "2015-03-23T13:50:52.16",
            "Query": null,
            "StorageLocation": "indexedDB",
            "IndexedDB": "{\"keys\": \"++\", \"pk\":\"AddressID\"}"
        }
    }
};

Unit Test

describe("Testing service", function(){
    var noHTTP, $httpBackend, $rootScope;

    beforeEach(function(){
        module("module.http");

        inject(function($injector){
            $httpBackend = $injector.get("$httpBackend");
            noHTTP = $injector.get("noHTTP");
            $rootScope = $injector.get("$rootScope");
        })
    }); 

    describe("Testing INOCRUD transport inteface", function(){

        it("should successfully post a new record to the create endpoint.", function(done){
            var iNoCRUD = noHTTP.createTransport();

            $httpBackend
                .when("POST", CRUD.POST.request.url, angular.toJson(CRUD.POST.request.data))
                .respond(201, CRUD.POST.response, CRUD.POST.request.headers );

            $rootScope.$apply(function(){
                iNoCRUD.create(CRUD.POST.request.url, CRUD.POST.request.data)
                    .then(function(data){
                        expect(data).toEqual(CRUD.POST.response);
                        done();                 
                    })
                    .catch(function(err){                   
                        console.log(err);               
                        done(); 
                    });             
            });



            $httpBackend.flush();
        });
    });
});

karma.config.js

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',


    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],


    // list of files / patterns to load in the browser
    files: [
        'node_modules/angular/angular.js',
        'node_modules/angular-mocks/angular-mocks.js',
        'bower_components/ng-lodash/build/ng-lodash.js',
        'test/mock/*.*',
        'test/http.spec.js',
        'src/http.js'
    ],


    // list of files to exclude
    exclude: [
    ],


    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
    },


    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['verbose'],


    // web server port
    port: 9876,


    // enable / disable colors in the output (reporters and logs)
    colors: true,


    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,


    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,


    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['PhantomJS'],


    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false
  });
};
  • Possible duplicate of [AngularJS+Jasmine: $httpBackend not working as expected](https://stackoverflow.com/questions/21577718/angularjsjasmine-httpbackend-not-working-as-expected) – Paul Sweatte Jul 11 '17 at 00:34

0 Answers0