【问题标题】:Unit testing $httpBackend angular no response defined单元测试 $httpBackend 角度未定义响应
【发布时间】:2016-03-31 10:01:29
【问题描述】:

我在第一次测试中遇到了困难,所以请多多包涵。 我想测试一个发布 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 !

我觉得我已经很接近了,但我无法让它发挥作用。如果你能帮助我,我将不胜感激。谢谢!

【问题讨论】:

    标签: angularjs unit-testing jasmine karma-runner


    【解决方案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 案例)时很有用,因此您可以删除它,您的测试仍然会通过.)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多