【问题标题】:Angular Unit Testing Directive for Input Restriction用于输入限制的 Angular 单元测试指令
【发布时间】: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


    【解决方案1】:

    您似乎仍然选择了旧的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');
        });
    

    asyncawait fixture.whenStable() 可以是可选的。首先尝试在没有这些的情况下进行操作,看看它是否有效。如果不是,请添加 asyncfixture.whenStable(),因为我记得 Angular 表单的某些方面是异步的。

    【讨论】:

      猜你喜欢
      • 2013-10-18
      • 2020-02-29
      • 1970-01-01
      • 2015-01-18
      • 2015-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-10
      相关资源
      最近更新 更多