0

我有一项服务可以发布关于创建的帖子,如下所示:

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'});
}

然而,当我去测试我的一些使用这个模块和服务的控制器时,它们都立即失败并出现错误Unexpected request: POST /example/path

如果我postInitCommands()在服务创建中调用 to,这个错误就会消失,我可以测试我的控制器。

我的 qunit 设置如下:

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() {

    }
});
4

1 回答 1

1

您的服务实例是在您调用injector.get('dataService'). POST 是在发生这种情况时进行的,因此您需要告诉您的测试在该行之前期待 HTTP 请求。

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() {

    }
});
于 2013-10-30T19:53:03.780 回答