加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 在角度形式指令的单元测试中设置视图值输入字段

发布时间:2020-12-17 08:28:05 所属栏目:安全 来源:网络整理
导读:我有一个指令,构建一个表单: app.directive('config',function() { return { restrict: 'E',scope: { data: '=' },template: 'form name="configForm"' + 'input type="number" max="10" ng-model="config.item" name="configItem"/' + 'div class="form-e
我有一个指令,构建一个表单:
app.directive('config',function() {
  return {
    restrict: 'E',scope: {
      data: '='
    },template: '<form name="configForm">' +
      '<input type="number" max="10" ng-model="config.item" name="configItem"/>' +
      '<div class="form-error" ng-show="configForm.$error.max">Error</div>' + 
      '</form>',controller: 'ConfigDirectiveController',};
});

我想做的是通过单元测试验证错误消息将显示给定一些输入。使用angular 1.2我可以修改$ scope.config.item,它会更新视图值和显示错误。

就像我可以告诉,用角度1.3,如果模型没有通过验证视图值不会更新…所以我需要修改视图值,以确保错误消息显示。

我如何访问“configItem”输入,以便我可以设置视图值,以确保错误消息将显示?

编辑以显示单元测试

我看到该值设置正确,但错误仍然有一个ng-hide应用于标签。当我查看页面并手动更改输入值时,ng-hide将被删除,如果输入大于10的内容,将显示错误。

beforeEach(inject(function($compile,$rootScope) {
      element = angular.element('<config data="myData"></config>');
      $scope = $rootScope.$new();
      $scope.myData = {};
      element = $compile(element)($scope);
    }));

    it('should warn that we have a large number',function() {
      var input = element.find('[name="configItem"]')[0];
      $scope.$apply(function() {
        angular.element(input).val('9000000001');
      });
      errors = element.find('[class="form-error ng-binding"]');
      expect(errors.length).toBe(1);
    })
下面是我对单元测试基于输入的指令的方法(为了清楚起见,省略了很多代码)。你重要的是:
angular.element(dirElementInput).val('Some text').trigger('input');

这里是完整的单元测试:

it('Should show a red cross when invalid',function () {

    dirElement = angular.element('<ng-form name="dummyForm"><my-text-entry ng-model="name"></my-text-entry></ng-form>');

    compile(dirElement)(scope);
    scope.$digest();

    // Find the input control: 
    var dirElementInput = dirElement.find('input');

    // Set some text!
    angular.element(dirElementInput).val('Some text').trigger('input');
    scope.$apply();

    // Check the outcome is what you expect! (in my case,that a specific class has been applied)
    expect(dirElementInput.hasClass('ng-valid')).toEqual(true);
  });

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读