我正在尝试对我的 Angular 控制进行测试。如何测试函数中的变量?
例子:
$scope.onFileSelect = function($files) {
$scope.selectedFiles = [];
$scope.progress = [];
if ($scope.upload && $scope.upload.length > 0) {
for (var i = 0; i < $scope.upload.length; i++) {
if ($scope.upload[i] !== null) {
$scope.upload[i].abort();
}
}
}
$scope.upload = [];
$scope.uploadResult = [];
$scope.selectedFiles = $files;
$scope.dataUrls = [];
if ($scope.selectedFiles.length==1) {
for ( var i = 0; i < $files.length; i++) {
var $file = $files[i];
if (window.FileReader && $file.type.indexOf('image') > -1) {
var fileReader = new FileReader();
fileReader.readAsDataURL($files[i]);
var loadFile = function(fileReader, index) {
fileReader.onload = function(e) {
$timeout(function() {
$scope.dataUrls[index] = e.target.result;
});
};
}(fileReader, i);
}
$scope.progress[i] = -1;
if ($scope.uploadRightAway) {
$scope.start(i);
}
}
}
else{
$scope.selectedFiles = null;
$scope.clientmsg={};
$scope.errormessageheader="";
$scope.uploadErrors="";
$scope.UploadSuccess="";
auxArray = [""];
$scope.uploadErrors =auxArray;
$scope.errormessageheader="Only_submit_one_file";
}
};
还有我的测试...
describe('Unit: routeAssignUpload_Ctrl', function () {
beforeEach(angular.mock.module('primaryDistributionApp'));
var ctrl, scope;
// inject the $controller and $rootScope services
// in the beforeEach block
beforeEach(inject(function($controller, $rootScope) {
// Create a new scope that's a child of the $rootScope
scope = $rootScope.$new();
// Create the controller
ctrl = $controller('routeAssignUpload_Ctrl', {
$scope: scope
});
}));
it('probando funcion onFileSelect',function(){
expect(scope.onFileSelect).toBeDefined();
var onFileSelect1 = new scope.onFileSelect;
spyOn(onFileSelect1).andCallThrough();
expect(scope.upload).toBeDefined();
});
})
结果是“TypeError: 'undefined' is not an object”(评估 '$scope.selectedFile 长度') 我不明白为什么,谁能帮助我?
最佳答案
需要考虑的几件事。
- 为什么在尝试调用
scope.onFileSelect
时要使用new
关键字?这只是一个作用域方法,您不需要(也可能不想)将其用作构造方法。 - 您没有将任何变量传递到
scope.onFileSelect
。这意味着$files
变量是undefined
。然后通过$scope.selectedFiles = $files;
分配它并测试它的长度 (if ($scope.selectedFiles.length==1) { ... }
) .如错误所示,undefined
没有length
属性。
我也没有看到任何需要监视 onFileSelect
的理由——您正在测试它的行为,并且您正在直接调用它;使用 spyOn(..).andCallThrough
是最有用的,当你想测试一些其他函数为你调用它,而不打断它的行为。您的测试可能会更好地编写如下(充实以测试更有趣的行为):
it('probando funcion onFileSelect',function(){
var files = ['fileA', 'fileB'];
expect(scope.onFileSelect).toBeDefined();
scope.onFileSelect(files);
expect(scope.selectedFiles).toBe(files);
expect(scope.upload).toBeDefined(); // or whatever
});
您应该问自己的问题是您真正想要测试的行为是什么。目前,这不是一个非常有趣的测试——您知道 upload
已定义,但您还不知道任何有趣的事情。
关于javascript - 如何测试 Angular $scope 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24702288/