【问题标题】:Angular unit testing form validation - control stays untouchedAngular 单元测试表单验证 - 控制保持不变
【发布时间】:2019-01-30 14:31:30
【问题描述】:

我有一个具有表单验证功能的 Angular 组件。我正在进行单元测试,以确保在输入无效时显示错误消息。

但是当我尝试更改<input> 框的值时,控件的状态仍然是untouched,并且不显示错误。

代码如下:

<form #zipForm="ngForm">
<label>
    <input type="text" id="postalCode" [(ngModel)]="postalCode" #postalCodeElem="ngModel" name="postalCode" [pattern]="validationPattern" required>
    <button type="button" (click)="click(postalCodeElem.value)">Enroll</button>
    <div *ngIf="postalCodeElem.invalid && postalCodeElem.touched">
    <span id="required-postal-code" *ngIf="postalCodeElem?.errors?.required">
        zip/postal code is required
    </span>
    <span id="invalidPostalCode" *ngIf="postalCodeElem?.errors?.pattern">
        zip postal code is invalid
    </span>
    </div>
</label>
</form>

测试文件:

it('should show error in case of invalid postal code', () => {
    const elem: HTMLElement = fixture.nativeElement;
    const inputElem: HTMLInputElement = elem.querySelector('input');

    inputElem.value = 'L5L2';
    inputElem.dispatchEvent(new Event('input', { bubbles: true }));

    fixture.detectChanges();

    const invalidErrorElem: any = elem.querySelector('span');

    console.log('elem', elem);
    console.log('invalidErrorElem', invalidErrorElem);

    expect(invalidErrorElem).not.toBeNull();
});

我创建了一个 stackblitz 来演示这个问题:https://stackblitz.com/edit/angular-testing-45zwkn?file=app%2Fapp.component.spec.ts

知道我做错了什么吗?

【问题讨论】:

    标签: angular unit-testing testing jasmine


    【解决方案1】:

    您需要集中注意力并模糊您的输入:

    inputElem.focus();
    fixture.componentInstance.postalCode = 'L5L2';
    inputElem.blur();
    fixture.detectChanges();
    

    【讨论】:

    • 我试过了,它似乎也不起作用。 stackblitz.com/edit/…
    • 哦,我的错,我没有意识到你隐藏了错误消息,直到它被触摸。您需要聚焦输入然后模糊。这就是它没有出现的原因。
    • 嘿,效果很好。您能否编辑您的答案并将其放在那里以便我可以接受您的答案?谢谢你的帮助!!
    猜你喜欢
    • 2019-12-18
    • 1970-01-01
    • 2016-07-29
    • 2016-05-05
    • 1970-01-01
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    相关资源
    最近更新 更多