我有一个服务,可以创建一个帖子,如下所示:
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()
的调用,则此错误消失,我可以测试我的控制器。
我的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() {
}
});
答案 0 :(得分: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() {
}
});