代码之家  ›  专栏  ›  技术社区  ›  Francesco Borzi

测试无效表单时未显示角度错误文本

  •  0
  • Francesco Borzi  · 技术社区  · 7 年前

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

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

    enter image description here

    这是我编写的测试用例:

    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.');
    });
    

    尽管我用了 fixture.detectChanges() 在发送 input 事件,并且尽管窗体控件状态无效并且有错误(我通过调试代码检查),但在测试运行期间不会显示错误消息,因此预期失败。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Francesco Borzi    7 年前

    问题是,在用户从字段中移出之前(例如,单击其他位置或按TAB键),错误消息实际上不会显示。

    inputElement 派遣 模糊 活动:

    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.');
    });
    
    推荐文章