[英]Adding validators in angular forms
我正在測試此html表單:
<input #nhcInput type="text" class="form-control" name="nhc" id="field_nhc" [(ngModel)]="paciente.nhc" maxlength="38" pattern="[0-9]+"/> <div [hidden]="!(editForm.controls.nhc?.dirty && editForm.controls.nhc?.invalid)"> <small class="form-text text-danger" [hidden]="!editForm.controls.nhc?.errors?.maxlength" jhiTranslate="entity.validation.maxlength" translateValues="{ max: 38 }"> This field cannot be longer than 38 characters. </small>
TEH RESULT {{nhcInput.className}} //This line prints ng-valid/ dirty, touched correctly
我的組件中有這個:
paciente: Paciente = {nhc: '23423' } as Paciente;
it ('NHC cannot have more than 38 characters', async(() => { comp.paciente.nhc = 'rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr' ; console.log(fixture.nativeElement.querySelector('input[name="nhc"]').className); fixture.detectChanges(); expect(fixture.nativeElement.querySelector('input[name="nhc"]').className.includes('ng-invalid')).toEqual(true); }));
現在,我想通過檢查驗證程序來測試有效性。 console.log因為沒有找到驗證器,所以只打印出窗體控制,而沒有驗證器的類型。
我在組件中放置了一個用於此fild的驗證器:
@ViewChild('editForm') editForm: any; editform.controls["nhc"].setValidators([ Validators.maxLength(38)]);
但這不起作用。 我在這里做錯什么嗎?
謝謝!
您的問題來自於這樣一個事實,即您沒有按順序進行操作,也不依賴框架進行測試。
我制作了一個具有測試功能的沙盒 ,隨時查看。 現在進行解釋:
讓我們從組件開始:
@Component({
selector: 'hello',
template: `
<form #myForm="ngForm">
<input type="text" maxlength="20" name="patient" id="patient" [(ngModel)]="patient">
</form>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@ViewChild('myForm') myForm: NgForm;
patient: string;
}
一個非常簡單的組件,具有模板驅動的表單以及基本的驗證和綁定。
如果你這樣做
ngOnInit() {
console.log(this.myForm.controls);
setTimeout(() => console.log(this.myForm.controls));
}
您將同時看到undefined
和{ patient: FormControl }
。 發生這種情況是因為您在執行測試之前不等待視圖初始化。 這意味着測試找不到表單控件,因此無法通過。
現在進行測試:
import { Component } from '@angular/core';
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { HelloComponent } from './hello.component';
import { FormsModule } from '@angular/forms';
describe('HelloComponent', () => {
let fixture: ComponentFixture<HelloComponent>;
let component: HelloComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [HelloComponent]
});
fixture = TestBed.createComponent(HelloComponent);
component = fixture.debugElement.children[0].componentInstance;
fixture.detectChanges();
});
it('should be invalid with more than 20 chars', async(() => {
setTimeout(() => {
component.myForm.controls['patient'].setValue('ddddddddddddddddddddd'); // 21
fixture.detectChanges();
expect(component.myForm.control.invalid).toEqual(true);
});
}));
});
開始非常基本,已配置測試台並檢測到更改。
現在是您要測試的部分:首先必須等待組件加載超時,然后才需要使用框架在表單上設置值:
component.myForm.controls['patient'].setValue('ddddddddddddddddddddd'); // 21
此接口輸入21 d
到輸入,這是使其無效。 之后,您需要觸發更改檢測,現在您可以使用
expect(component.myForm.control.invalid).toEqual(true);
這將以表單作為控件,這意味着它具有FormControl擁有的所有屬性和功能。 其中,您可以找到invalid
屬性,該屬性指出您的控件是否處於無效狀態。
同樣,我必須指出這種測試是無用的,因為您基本上是在嘗試查看框架是否正常運行。 那不是你的工作,那是Angular團隊的工作。 如果您想測試某項內容,則應測試該表單處於無效狀態時無法提交該表單,這是一種業務規則(我想),並且可以防止副作用(與該測試不同)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.