unit-testing – 测试自定义验证角度指令

前端之家收集整理的这篇文章主要介绍了unit-testing – 测试自定义验证角度指令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这个自定义验证指令是在官方角点的一个例子。
http://docs.angularjs.org/guide/forms
它检查文本输入是否是数字格式。
  1. var INTEGER_REGEXP = /^\-?\d*$/;
  2. app.directive('integer',function() {
  3. return {
  4. require: 'ngModel',link: function(scope,elm,attrs,ctrl) {
  5. ctrl.$parsers.unshift(function(viewValue) {
  6. if (INTEGER_REGEXP.test(viewValue)) {
  7. // it is valid
  8. ctrl.$setValidity('integer',true);
  9. return viewValue;
  10. } else {
  11. // it is invalid,return undefined (no model update)
  12. ctrl.$setValidity('integer',false);
  13. return undefined;
  14. }
  15. });
  16. }
  17. };
  18. });

要单元测试这段代码,我写道:

  1. describe('directives',function() {
  2. beforeEach(module('exampleDirective'));
  3.  
  4. describe('integer',function() {
  5. it('should validate an integer',function() {
  6. inject(function($compile,$rootScope) {
  7. var element = angular.element(
  8. '<form name="form">' +
  9. '<input ng-model="someNum" name="someNum" integer>' +
  10. '</form>'
  11. );
  12. $compile(element)($rootScope);
  13. $rootScope.$digest();
  14. element.find('input').val(5);
  15. expect($rootScope.someNum).toEqual(5);
  16. });
  17. });
  18. });
  19. });

然后我得到这个错误

  1. Expected undefined to equal 5.
  2. Error: Expected undefined to equal 5.

我把打印语句放在任何地方看看发生了什么,它看起来像指令从来没有调用
什么是测试这样简单的指令的正确方法

另一个答案的测试应该写成:
  1. describe('directives',function() {
  2. var $scope,form;
  3. beforeEach(module('exampleDirective'));
  4. beforeEach(inject(function($compile,$rootScope) {
  5. $scope = $rootScope;
  6. var element = angular.element(
  7. '<form name="form">' +
  8. '<input ng-model="model.somenum" name="somenum" integer />' +
  9. '</form>'
  10. );
  11. $scope.model = { somenum: null }
  12. $compile(element)($scope);
  13. form = $scope.form;
  14. }));
  15.  
  16. describe('integer',function() {
  17. it('should pass with integer',function() {
  18. form.somenum.$setViewValue('3');
  19. $scope.$digest();
  20. expect($scope.model.somenum).toEqual('3');
  21. expect(form.somenum.$valid).toBe(true);
  22. });
  23. it('should not pass with string',function() {
  24. form.somenum.$setViewValue('a');
  25. $scope.$digest();
  26. expect($scope.model.somenum).toBeUndefined();
  27. expect(form.somenum.$valid).toBe(false);
  28. });
  29. });
  30. });

注意$ scope。$ digest()现在在$ setViewValue之后被调用。这将形式设置为“脏”状态,否则它将保持“原始”,这可能不是你想要的。

猜你在找的Angularjs相关文章