我在第一次测试时遇到了困难所以请耐心等待。 我想测试一个创建http帖子的函数:
$scope.formData= 'client=' + $scope.client_selected + '&version=' + $scope.version_selected + '&modules=' + $scope.client.modules;
var response = $http.post('http://localhost:8080/mavenproject8/lol/form', $scope.formData);
response.success(function (data, status, headers, config) {
$scope.validity = true;
$scope.status = "true";
});
response.error(function (data, status, headers, config) {
$scope.status = "false";
alert("Exception details: " + JSON.stringify({data: data}));
我的测试看起来像这样:
...
beforeEach(inject(function ($injector) {
// Set up the mock http service responses
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when('POST', 'http://localhost:8080/mavenproject8/lol/form', data)
.respond([200, {success: true, errors: [{}]}]);
这是it
块:
it('should succeed when everything is correct', function () {
$rootScope.client.modules=["360"];
$rootScope.version_selected="2.4.0"
$rootScope.client_selected="NSM";
$rootScope.formData='client=' + $rootScope.client_selected + '&version=' + $rootScope.version_selected + '&modules=' + $rootScope.client.modules;
$httpBackend.expectPOST('http://localhost:8080/mavenproject8/lol/form',$rootScope.formData);
$rootScope.myFunc();
expect($rootScope.validity).toBe(true);
});
但是这个测试没有通过,错误:
Error: No response defined !
我觉得我太近了但是我无法让它发挥作用。如果你能帮助我,我将不胜感激。谢谢!
答案 0 :(得分:1)
实际上,您预期的帖子请求没有指定回复,这就是您看到错误的原因,所以您需要做的就是:
$httpBackend.expectPOST('http://localhost:8080/mavenproject8/lol/form').respond(200,{});
//don't forget to make the flush after the function call.!!
$rootScope.myFunc();
$httpBackend.flush();
(你可以不需要$ httpBackend.whenPost,因为当你想要创建一个后端定义并指定响应(例如get
个案例)时这很有用,所以你可以删除它,你的考试仍然会通过。)