【问题标题】:angularjs unit test [orderBy:notarray] Expected array but receivedangularjs 单元测试 [orderBy:notarray] 预期的数组但已收到
【发布时间】:2017-12-29 11:27:50
【问题描述】:

我正在为 angularjs 编写单元测试,这里有一个我无法弄清楚的错误。

这是控制器:

controller('MetricController', function($scope, $interval, $http, $filter, $routeParams, ServiceEnum, DateTimeFormatter, RefreshInterval) {
    $scope.categories = {};
    $scope.dataset = {};
    $scope.attrs = {};
    $scope.loadData = function() {
        $http.get(ServiceEnum.Metrics).then(function processResponse(result) {
            $scope.metricsUnsortedData = result.data;
            $scope.metricsData = $filter('orderBy')($scope.metricsUnsortedData, 'instanceName'); 

        })
        .catch(function processError(error) {
            $scope.metricsUnsortedData = error;
        });      
    };

    $scope.loadData();     
});

这是我的单元测试。我想测试一下能不能成功返回数据:

    it('should get data successfully', function() {
        $httpBackend
            .when('GET', 'http://localhost/foo')
            .respond(200, { foo: 'bar' });
        $httpBackend.flush();
        expect(scope.metricsUnsortedData).toEqual({ foo: 'bar' });
    });

错误是:
预期错误:[orderBy:notarray] 预期数组但已收到:{"foo":"bar"} http://errors.angularjs.org/1.6.4/orderBy/notarray?p0=%7B%22foo%22%3A%22bar%22%7D 等于 { foo : 'bar' }。 错误:预期错误:[orderBy:notarray] 预期数组但收到:{“foo”:“bar”} http://errors.angularjs.org/1.6.4/orderBy/notarray?p0=%7B%22foo%22%3A%22bar%22%7D 等于 { foo : 'bar' }。 在对象。 (components/metrics/metricsTest.js:97:47)

我不知道为什么会这样。之前的单元测试可以通过,这次我只在controller中添加了$filter,但是失败了。希望有人能给我一些建议。

谢谢

【问题讨论】:

    标签: angularjs unit-testing filter jasmine karma-jasmine


    【解决方案1】:

    $filter('orderBy') 函数必须对数组进行操作,而不是对象或任何其他类型。通过模拟$httpBackend 以返回{ foo: 'bar' }(一个对象)作为请求的数据,result.data 因此$scope.metricsUnsortedData 最终成为{ foo: 'bar' } 对象。

    相反,让模拟后端是一个空数组或类似的。

    it('should get data successfully', function() {
        $httpBackend
            .when('GET', 'http://localhost/foo')
            .respond(200, []);
        $httpBackend.flush();
        expect(scope.metricsUnsortedData).toEqual([]);
    });
    

    【讨论】:

    • "通过模拟 $httpBackend..."? $httpBackend 不是/不是模拟,它是一个拦截器。事实上,测试本身是错误的,因为它没有测试预期的错误! :)
    猜你喜欢
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2019-03-20
    相关资源
    最近更新 更多