【问题标题】:Angular error text not displayed when testing invalid form测试无效表单时不显示角度错误文本
【发布时间】:2019-05-29 02:10:29
【问题描述】:

在我的 Angular 应用程序中,我有一个简单的组件,其中包含一个带有文本输入字段的表单。

此输入字段仅接受少于 255 个字符的字符串。当用户插入超过 255 个字符的文本时,会显示错误:

这是我写的测试用例:

it('should display error when the inserted description text is too long', () => {
  const inputElement: HTMLInputElement = hostElement.querySelector('.input-element');

  inputElement.value = getRandomString(256);
  inputElement.dispatchEvent(new Event('input'));
  fixture.detectChanges();

  const errorElement: HTMLElement = hostElement.querySelector('.error-element');

  expect(errorElement).toBeTruthy();
  expect(errorElement.innerText).toContain('Please enter no more than 255 characters.');
});

尽管我在调度input 事件后使用fixture.detectChanges(),并且尽管表单控件状态为无效并且有错误(我通过调试代码进行了检查),但测试时未显示错误消息运行,所以期望失败。

【问题讨论】:

    标签: angular typescript angular-forms angular-test


    【解决方案1】:

    问题在于,直到用户离开该字段(例如单击其他位置或按 TAB 键),错误消息实际上才显示。

    所以为了解决这个问题,我们需要 inputElement 来调度 blur 事件:

    inputElement.dispatchEvent(new Event('blur'));

    测试现在看起来像这样:

    it('should display error when the inserted description text is too long', () => {
      const inputElement: HTMLInputElement = hostElement.querySelector('.input-element');
    
      inputElement.value = getRandomString(256);
      inputElement.dispatchEvent(new Event('input'));
      inputElement.dispatchEvent(new Event('blur')); // this line has been added
      fixture.detectChanges();
    
      const errorElement: HTMLElement = hostElement.querySelector('.error-element');
    
      expect(errorElement).toBeTruthy();
      expect(errorElement.innerText).toContain('Please enter no more than 255 characters.');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多