如何解决输入限制的角单元测试指令
我有一条指令,限制用户输入特殊字符。尝试编写可验证用户是否可以输入特殊字符的单元测试。
在下面,我尝试模拟当用户输入A @时的按键事件,并且仅需要测试允许输入A。看起来输入没有通过事件用这些值更新。 console.log(input.value)打印空字符串。设置值的唯一方法是input.value,但在那种情况下,我也可以设置特殊字符,这不是我想要的。
是否能够反映用户的输入并进行验证以确保不允许使用特殊字符?
it('should not allow special chars',() => {
component.regexInput = '[a-zA-Z0-9\-\_ ]{1,25}';
fixture.detectChanges();
const input = fixture.nativeElement.querySelector('input');
const event = new KeyboardEvent("keydown",{
"key": "A"
});
input.dispatchEvent(event);
fixture.detectChanges();
const event2 = new KeyboardEvent("keydown",{
"key": "@"
});
input.dispatchEvent(event2);
fixture.detectChanges();
console.log(input.value);
expect(input.value).toEqual('A');
});
解决方法
似乎您仍然选择了旧的input
。
尝试:
it('should not allow special chars',async () => {
component.regexInput = '[a-zA-Z0-9\-\_ ]{1,25}';
fixture.detectChanges();
const input = fixture.nativeElement.querySelector('input');
const event = new KeyboardEvent("keydown",{
"key": "A"
});
input.dispatchEvent(event);
fixture.detectChanges();
const event2 = new KeyboardEvent("keydown",{
"key": "@"
});
input.dispatchEvent(event2);
fixture.detectChanges();
await fixture.whenStable();
const newInput = fixture.nativeElement.querySelector('input'); // grab a new reference here
console.log(newInput.value);
expect(newInput.value).toEqual('A');
});
async
和await fixture.whenStable()
可以是可选的。首先尝试在没有这些功能的情况下执行此操作,然后查看它是否有效。如果没有,请添加async
和fixture.whenStable()
,因为我记得Angular表单的某些方面是异步的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。