angular - 测试无效表单时不显示角度错误文本
问题描述
在我的 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 并且有错误(我通过调试代码进行了检查),但在测试运行时未显示错误消息,因此预期失败。
解决方案
问题是在用户离开该字段(例如单击其他地方或按 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.');
});
推荐阅读
- delphi - 拖放到远程桌面会话中的应用程序
- javascript - Fabricjs:在画布上更新 SVG
- sql-server - SQL Server 视图不是可移植的吗?
- vba - 如果存在特定值,则对宏 VBA 代码进行一些修改以删除行
- dart - 如何检查 Flutter 应用程序是否在前台?
- c# - 带有数据源的 Asp 日历重复标签
- java - 使用 AWS S3 作为监控平台的中间存储层
- javascript - 使用“opacityDecayVelocity”属性配置纸纹
- kubernetes - 从 kubectl logs -f 的大量日志中拖尾几行
- r - 如何设置y轴的小数位?