我是 Angular 测试的新手。
我想用一个表单(有效表单、必填表单等)测试所有场景
这是我的 html:
<div class="content" *ngIf="!recordsFound">
<div class="alert">
<span>OOOPS! No recordings found. You can add a new one:</span>
</div>
<form [formGroup]="recordingForm" #formDirective="ngForm" id="recordingForm">
<div>
<div>
<mat-form-field>
<mat-label>Artist*</mat-label>
<input matInput placeholder="Artist" formControlName="artist" />
<mat-error>Required input</mat-error>
</mat-form-field>
</div>
<div>
<mat-form-field>
<mat-label>Title*</mat-label>
<input matInput placeholder="Title" formControlName="title" />
<mat-error>Required input</mat-error>
</mat-form-field>
</div>
<div>
<mat-form-field>
<mat-label>ISRC</mat-label>
<input matInput placeholder="ISRC" formControlName="isrc" />
</mat-form-field>
</div>
<div>
<mat-form-field>
<mat-label>Duration</mat-label>
<input matInput placeholder="Duration" formControlName="duration" />
</mat-form-field>
</div>
<button mat-stroked-button color="primary" (click)="save()" [disabled]="!recordingForm.valid">
Add recording <mat-icon>music_note</mat-icon>
</button>
</div>
</form>
</div>
示例,测试表单是否有效且必填字段不为空:
it ('check if form is valid and required fields not empty',() =>{
const fixture = TestBed.createComponent(AddRecordingComponent);
const formArtistElement: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#recordingForm').querySelectorAll('input')[0];
const formTitleElement: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#recordingForm').querySelectorAll('input')[1];
formArtistElement.value='Rihanna';
formTitleElement.value='Umbrella';
formArtistElement.dispatchEvent(new Event('input'));
formTitleElement.dispatchEvent(new Event('input'));
const isFormValid = fixture.componentInstance.recordingForm.valid;
fixture.whenStable().then(() => {
expect(isFormValid).toBeTruthy();
})
});
我收到此错误:TypeError: Cannot read property 'querySelectorAll' of null
如何通过规范文件访问表单?
谢谢
答案 0 :(得分:1)
请试试这个
it ('check if form is valid and required fields not empty',() =>{
const fixture = TestBed.createComponent(AddRecordingComponent);
let component = fixture.componentInstance;
component.recordsFound = false; // To make form visible
fixture.detectChanges();
const formArtistElement: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#recordingForm')?.querySelectorAll('input')[0];
const formTitleElement: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#recordingForm')?.querySelectorAll('input')[1];
if(formArtistElement) {
formArtistElement.value='Rihanna';
formTitleElement.value='Umbrella';
formArtistElement.dispatchEvent(new Event('input'));
formTitleElement.dispatchEvent(new Event('input'));
const isFormValid = fixture.componentInstance.recordingForm.valid;
}
fixture.whenStable().then(() => {
expect(isFormValid).toBeTruthy();
})
});