【发布时间】:2020-12-08 22:42:00
【问题描述】:
我有一个指令限制用户输入特殊字符。尝试编写一个单元测试来验证以确保用户无法输入特殊字符。
下面我试图在用户输入 A@ 时模拟 keydown 事件 - 并且需要测试只允许输入 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');
});
【问题讨论】:
标签: unit-testing angularjs-directive karma-jasmine