[英]Trouble unit testing angular reactive form control reset from button click
我在為我的 Angular 應用程序編寫 jasmine 單元測試用例時遇到了問題。 有一個響應式表單並嘗試通過單擊按鈕重置特定表單控件。 即使場景應該足夠簡單以進行測試,但我似乎在這里遺漏了一些東西。
以下是應用程序的代碼片段。
app.component.html:
<form [formGroup]="userForm" novalidate (ngSubmit)="onSubmit()">
<div>
<input
type="text"
id="fNameFld"
name="fName"
formControlName="fName"
placeholder="First Name"
/>
<button (click)="clearField('fName')" id="clrFName">
Clear First Name
</button>
</div>
<div>
<input
type="text"
id="lNameFld"
name="lName"
formControlName="lName"
placeholder="Last Name"
/>
<button (click)="clearField('lName')" id="clrLName">Clear Last Name</button>
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
app.component.ts
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
name = 'Angular ' + VERSION.major;
userForm: FormGroup;
constructor(private readonly fb: FormBuilder) {}
ngOnInit() {
this.userForm = this.fb.group({
fName: this.fb.control(null),
lName: this.fb.control(null),
});
}
onSubmit() {
console.log('Submitted Data', this.userForm.value);
}
clearField(controlName: string) {
this.userForm.get(controlName).reset();
}
}
單元測試代碼
it('should clear fName control when the "Clear First Name" button is clicked', () => {
const spy = spyOn(component, 'clearField');
const clearBtn = fixture.debugElement.query(By.css("button#clrFName"));
const form = component.userForm;
form.patchValue({
'fName': 'John,
'lName': 'Doe'
});
clearBtn.nativeElement.click();
fixture.detectChanges();
expect(spy).toHaveBeenCalledTimes(1); // passes
expect(spy).toHaveBeenCalledWith('fName'); // passes
expect(form.get('fName').value).toBeNull(); // fails: Expected 'John' to be null.
});
角度:10.0.14
角 CLI:10.0.8
StackBlitz: https ://angular-ivy-fc6rik.stackblitz.io
好像你嘲笑clearField
。 添加它以在您模擬它時實際執行它的內容:
const spy = spyOn(component, 'clearField').and.callThrough();
所以每次clearField
時,它都會觸發 spy(這樣你就知道它是否被調用了),並且會執行它的 content 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.