我在使用 Jasmine 在 AngularJs 中测试 HTTP POST 时遇到了一些问题。
我有一个看起来像这样的 Controller :-
appControllers.controller("TaskAddController", function ($scope, $http) {
$scope.task = {};
$scope.messages = {};
$scope.actions = {
save : function() {
$http.post("/ajax/tasks/save", $scope.task)
.then(function() {
$scope.messages.success = true;
$scope.task = {};
});
}
};
});
我正在这样测试它:-
describe("TaskAddController", function() {
var createController, scope, $httpBackend;
beforeEach(function () {
module('appControllers');
scope = {};
inject(function ($injector) {
$httpBackend = $injector.get("$httpBackend");
});
inject(function ($controller) {
createController = function () {
return $controller("TaskAddController", { $scope: scope });
};
});
});
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it("when actions.save is called then should call service", function () {
var task = {
title: "Title",
description: "Description"
};
$httpBackend.expectPOST("/ajax/tasks/save", task);
createController();
scope.task = task;
scope.actions.save();
$httpBackend.flush();
});
});
这导致我收到以下错误 Error: No pending request to flush !
我做错了什么?
谢谢。
最佳答案
您使用的是哪个版本的 AngularJS?
当我运行代码时,我得到:错误:未定义响应!
当我添加响应时,测试通过:
$httpBackend.expectPOST("/ajax/tasks/save", task).respond({});
关于javascript - AngularJS 模拟 $http 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21764981/