我有一个带有http请求的控制器。成功时它调用另一个函数,我不知道如何测试它。我是棱角分明的新人。
var app = angular.module('myApp', ['']);
app.controller('MainController', ['$scope', '$http', function ($scope, $http) {
$scope.source = '';
$scope.destination = '';
var selectedFiles = [];
$scope.deleteFiles = function(source) {
if (source == $scope.source) {
selectedFiles = selectedFilesSource;
} else if (source == $scope.destination) {
selectedFiles = selectedFilesDestination;
}
$http({
method: 'POST',
url: 'deleteFiles.php',
data:
{
"sourcePath": source,
"selectedFiles": selectedFiles
}
}).success(function(data) {
if (source == $scope.source) {
$scope.showFiles(source, 'source');
} else if (source == $scope.destination) {
$scope.showFiles(source, 'destination');
}
});
};
我的测试文件是这样的:
describe("Testing to MainController", function(){
beforeEach(module('myApp'));
var mainController, scope, httpBackend, http;
beforeEach(inject(function($controller, $rootScope, $httpBackend, $http) {
scope = $rootScope;
httpBackend = $httpBackend;
http = $http;
httpBackend.when('POST', 'deleteFiles.php', function(data){return{"sourcePath": "source", "selectedFiles": ''}})
.respond(?????);
mainController = $controller('MainController', {
$scope: scope,
$http: http
});
}));
it('should call showFiles if sourcepath is source', function() {
scope.source = 'files/set1';
scope.deleteFiles('files/set1');
httpBackend.expectPOST('deleteFiles.php');
httpBackend.flush();
expect(scope.showFiles).toHaveBeenCalled();
});
});
错误消息:预计有间谍,但得到了功能。 我不知道如何在这里使用间谍,我不明白我应该在httpBackend中有什么。响应
答案 0 :(得分:0)
it('', function() {
spyOn(scope, 'showFiles');
scope.source = 'files/set1';
scope.deleteImages('images/set1');
// rest of your test ...
});
答案 1 :(得分:0)
如果您的承诺成功解决,则调用$scope.showFiles(source, 'source');
函数。所以在showFiles上创建一个间谍。
it('should call showFiles if sourcepath is source', function() {
spyOn(scope, 'showFiles');
scope.source = 'files/set1';
scope.deleteFiles('files/set1');
httpBackend.expectPOST('deleteFiles.php');
httpBackend.flush();
expect(scope.showFiles).toHaveBeenCalled();
});