【问题标题】:How to unit test for http request inside a function in directive如何在指令中的函数内对 http 请求进行单元测试
【发布时间】:2015-09-28 11:32:24
【问题描述】:

我在 http 请求中创建了一个函数,用于获取然后发布请求我如何测试该方法这里是我的指令控制器函数:

var getConfig = function () {
    if (!$scope.json) {
        $http.get('/schools/' + $scope.school.id + '/config?deployment_uuid=' + $scope.schoolId)
                .then(function (response) {
                    $scope.school.config = JSON.stringify(response.data, null, 4);
                });
    }
};

$scope.disable = function () {
    getConfig();
    $http.post('/school/' + $scope.school.id + '/update', {
        deployment_id: $scope.schoolId,
        component: $scope.schoolName,
        is_enabled: false,
        config: JSON.parse($scope.school.config)
    });
};

测试用例:

  describe('controller', function () {
        fit('should POST payload  for a scenario to disable', function () {
            $scope.school.config = JSON.stringify(mockSchoolConfig, null, 4);
            $scope.disable();
            $scope.$digest();
            $httpBackend.expect('POST', '/school/' + $scope.school.id + '/update', {
                deployment_id: $scope.schoolId,
                component: $scope.schoolName,
                is_enabled: false,
                config: $scope.school.config
            }).respond(200);
            //$httpBackend.flush();
        });
    });

Error: Unexpected request: GET /s/create-alarm/config?school_uuid=170bf60e-0153-4615-9a4e-a6bc3ad546ea

预计没有更多请求

如何测试这个函数和http请求?

【问题讨论】:

    标签: angularjs unit-testing directive


    【解决方案1】:

    在您的代码中,您混合了设置、请求和处理代码。虽然编写这样的代码很方便,但很难测试(正如您所注意到的)。解决方案是将代码分成几部分,可能每部分都分成一个不同的函数:

    var requestConfig() {
        return $http.get('/schools/' + $scope.school.id + '/config?deployment_uuid=' + $scope.schoolId);
    }
    
    var saveConfig(response) {
        $scope.school.config = JSON.stringify(response.data, null, 4);
    }
    
    var getConfig = function () {
        if (!$scope.json) {
            requestConfig()
                    .then(function (response) {
                        saveConfig();
                    });
        }
    };
    

    在您的测试中,您现在可以模拟这些函数。例如,您可以将requestConfig() 替换为只返回一个对象而不发出请求的函数。

    您可能还想避免使用像 $scope 这样的全局变量,而是通过函数参数传递信息,以便更轻松地编写测试。

    【讨论】:

      猜你喜欢
      • 2018-03-13
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 2016-07-25
      • 2013-06-10
      • 2017-08-08
      • 2017-06-05
      相关资源
      最近更新 更多