测试依赖于工厂的角度控制器

时间:2017-04-12 05:43:02

标签: angularjs unit-testing jasmine

我是Unit Testing的新手,我正在尝试测试依赖于工厂的控制器,该工厂调用URL来获取数据。

下面是我的控制器代码(sqResultReviewTable模块代码在一个单独的文件中):

    (function () {
angular.module('sqResultReviewTable')
       .controller('sqResultReviewTableController', fetchJsonData);  //fetchJsonData is the controller function name.
function fetchJsonData($scope, fetchDataFromJsonFile) {              // fetchDataFromJsonFile is the the service that return the data that is fetched fron the JSON file.
    labResultData = fetchDataFromJsonFile.getOrders().then(function (returnedArray) {   //function call to the service method getOrders and storing the resultant array in a varaible called labResultData.
        $scope.labResultData = returnedArray;                   //Assigning labresultData to the $scope.
        console.log($scope.labResultData);
    });
}
})()

这是我的工厂服务(工厂服务在一个单独的文件中):

    (function () {
angular.module('sqResultReviewTable')
.factory('fetchDataFromJsonFile', ['$http', function ($http) {
    return {
        getOrders: function () {                //getOrders is function which can be used to fetch data from the JSON file. It return an Array.
            return $http({
                method: 'GET',
                url: '/ResultReview/GetDataFromService',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(function (response) {
                return JSON.parse(response.data);           //Returning the array that is fetched from the JSON file.
            });
        }
    };
}]);
})();

以下是我尝试的测试用例:

    describe('sqResultReviewTable', function () {    
beforeEach(angular.mock.module('sqResultReviewTable'));
var $controller;
beforeEach(angular.mock.inject(function(_$controller_){
    $controller = _$controller_;
}));
describe('resultReviewTableController', function () {
    it('should have an array of length 4', function () {
        var $scope = {};
        var controller = $controller('sqResultReviewTableController', { $scope: $scope });
        var len = $scope.labResultData.length;
        expect(len).toBe(4);
    });
});
});

我收到此错误:     TypeError:无法读取属性' length'未定义的

对此有任何帮助表示赞赏。谢谢。

编辑1: 我也试过这种方式,但结果是一样的 TypeError:无法读取属性' length'未定义的

    describe('resultReviewTableController', function () {
beforeEach(module('sqResultReviewTable'));
var $scope;
describe('Table Controller', function () {
    beforeEach(inject(function ($rootScope, $controller) {
        $scope = $rootScope.$new();
        $controller('sqResultReviewTableController', {$scope : $scope});
    }));
    it('should contain an array of length 4', function () {
        expect($scope.labResultData.length).toBe(4);
    });
});
});

0 个答案:

没有答案