我的應用程式中有這樣一個表單,其中包含一個必填欄位,以及一個在該欄位不為空時啟用的按鈕。
上傳.component.html
<form [formGroup]="uploadForm" (ngSubmit)="Submit()">
<mat-form-field appearance="outline">
<mat-label translate>enter-name</mat-label>
<input matInput formControlName="name">
</mat-form-field>
<button mat-raised-button [disabled]="!uploadForm.valid">Send</button>
</form>
并上傳.component.ts:
ngOnInit() {
this.uploadForm = new FormGroup({
'name': new FormControl('', Validators.required),
);
}
我想測驗這個案例。
試試這個,upload.component.spec.ts:
it('should be ok', waitForAsync(() => {
let fixture = TestBed.createComponent(DashboardComponent);
fixture.detectChanges();
fixture.whenStable().then(() => {
let input = fixture.debugElement.nativeElement.querySelector('[matInput]');
input.value = 'someValue';
input.dispatchEvent(new Event('input'));
expect(fixture.debugElement.nativeElement.querySelector('button').disabled).toBeFalsy();
});
}));
不作業。
誰能幫我語法?
謝謝!
uj5u.com熱心網友回復:
我認為您缺少 afixture.detectChanges()自從模型更改以來。嘗試這個:
it('should be ok', waitForAsync(() => {
let fixture = TestBed.createComponent(DashboardComponent);
fixture.detectChanges();
fixture.whenStable().then(() => {
let input = fixture.debugElement.nativeElement.querySelector('[matInput]');
input.value = 'someValue';
input.dispatchEvent(new Event('input'));
// !! need another fixture.whenStable since some aspects of a form are asynchronous
fixture.whenStable().then(() => {
// !! add a fixture.detectChanges() since the model changed
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.querySelector('button').disabled).toBeFalsy();
});
});
}));
話雖這么說,但好處ReactiveForms是您不需要弄亂視圖。您可以只玩表單并獲得您想要的東西。
像這樣的東西:
it('should be ok', () => {
// !! first fixture.detectChanges() calls ngOnInit
fixture.detectChanges();
// !! change the model directly
component.uploadForm.get('name').setValue('someValue');
// !! update the view with fixture.detectChanges()
fixture.detectChanges();
expect(fixture.debugElement.nativeElement.querySelector('button').disabled).toBeFalsy();
});
我認為像 ^ 這樣的測驗更容易撰寫。
uj5u.com熱心網友回復:
您需要在 app.module 中添加 ReactiveFormsModule ,例如
從'@angular/forms'匯入 { FormsModule, ReactiveFormsModule };
并添加匯入
FormsModule, ReactiveFormsModule
我剛剛嘗試過stackblitz,它可以作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/491703.html
