首页 > 解决方案 > 测试无效表单时不显示角度错误文本

问题描述

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

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

标签: angulartypescriptangular-formsangular-test

解决方案


问题是在用户离开该字段(例如单击其他地方或按 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.');
});

推荐阅读