我有 xf 数组:var xf = [];
我有一个函数是这个数组中的一个元素和一个使用它的函数:
$scope.checkEmailValid = function () {
var result = false;
Iif (xf.validateEmail($scope.email, '256')) {
result = true;
}
return result;
};
xf.validateUsername = function (sText) {
var isValid = false;
do {
//Check for valid string.
isValid = typeof sText === 'string';
if (!isValid) {
break;
}
//Check that each special character does not exist in string.
for (var i = 0; i < sText.length; i++) {
if (xf.SPECIAL_CHARS.indexOf(sText.charAt(i)) !== -1) {
isValid = false;
break;
}
}
if (!isValid) {
break;
}
} while (false);
return isValid;
};
但是当我运行我的规范时:
it ('checkEmail', function(){
$controller('MyCtrl', { $scope: $scope });
xf.validateUsername();
spyOn(window,xf.validateUsername).and.callThrough();
});
报错:
xf.validateUsername is not a function
如何覆盖它?
最佳答案
xf
变量不可从 Controller 范围外访问(即不可在单元测试文件中访问)。
你一定做过以下事情:
angular
.module('myModule')
.controller(function ($scope) {
var xf = [];
// etc.
});
一旦 Angular 实例化它,您就可以将 xf
变量附加到 MyController 实例:
angular
.module('myModule')
.controller(function ($scope) {
this.xf = [];
// etc.
});
但这并不是真正干净的方法。更好的方法(在我看来)是创建一个工厂:
angular
.module('myModule')
.factory('xfService', function () {
var xf = [];
function validateUsername(text) {
// etc.
}
function get() {
return xf;
}
return {
get: get,
validateUsername: validateUsername
};
});
现在,您可以在 Controller 中注入(inject)工厂以使用 xf:
angular
.module('myModule')
.controller(function ($scope, xfService) {
// somewhere
var isValid = xfService.validateEmail($scope.email, '256');
// to get the values in the array
var values = xfService.get();
});
最后,对于单元测试,测试 validateEmail
方法变得非常容易。
describe('Unit tests - xfService', function () {
var xfService;
beforeEach(angular.module('myModule'));
beforeEach(angular.inject(function (_xfService_) {
xfService = _xfService_;
});
});
describe('xfService.validateUsername', function () {
it('should return a boolean value', function () {
// for example
expect(typeof xfService.validateUsername('test')).toBe('boolean');
});
// add more unit tests to check that the method works as expected
});
});
您需要将 angular-mocks
文件添加到 Karma 配置中。
感谢 Paul Podlech 和 Claies 在评论/答案中提供的提示。
关于javascript - 如何使用 Jasmine 在 AngularJS 中为数组函数创建单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31743717/