Search code examples
angularjshttp-postqunit

Service with post on creation


I have a service that does a post on creation, something like the following:

angular.module('app', ['$strap.directives'])
.service('dataService', function ($rootScope, $http, $location) {

    this.postInitCommands = function (path, command) {

        $http.post(path,
                   command,
                   {headers:{'Content-Type':'application/x-www-form-urlencoded'} 
            }).success(function (data, status, headers, config) {
                console.dir(data);
            });
    };

    this.postInitCommands("/example/path", {example: 'command'});
}

However, when I go to test some of my controllers that use this module and service, they all failed immediately with error Unexpected request: POST /example/path.

If I take out the call to postInitCommands() in the service creation, this error goes away and I can test my controllers.

My qunit setup is as follows:

var fittingDataServiceMock, injector, ctrl, $scope, $httpBackend;

module("Fitting Controller Test", {
    setup: function() {
        injector = angular.injector(['ngMock', 'ng','app']);
        $scope = injector.get('$rootScope').$new();
        dataServiceMock= injector.get('dataService');
        $httpBackend = injector.get('$httpBackend');
        $httpBackend.whenPOST('/example/test').respond(200, {});
        ctrl = injector.get('$controller')(DoubleVariableController, { $scope: $scope, dataService: dataServiceMock});
    },
    teardown: function() {

    }
});

Solution

  • Your service instance is constructed when you call injector.get('dataService'). The POST is made when that happens, so you need to tell your test to expect a HTTP request before that line.

    var fittingDataServiceMock, injector, ctrl, $scope, $httpBackend;
    
    module("Fitting Controller Test", {
        setup: function() {
            injector = angular.injector(['ngMock', 'ng','app']);
            $scope = injector.get('$rootScope').$new();
    
            $httpBackend = injector.get('$httpBackend');
            $httpBackend.whenPOST('/example/test').respond(200, {});
    
            dataServiceMock= injector.get('dataService');
            ctrl = injector.get('$controller')(DoubleVariableController, { $scope: $scope, dataService: dataServiceMock});
        },
        teardown: function() {
    
        }
    });