[英]Unable to get select button click in unit testing using Jasmine and Angular
您好,我正在使用 Angular 並嘗試為 Reactive 表單創建單元測試但無法成功
我需要什么:如何使用 angular 中的 jasmine 在表單填充了假值和真值后執行按鈕單擊。
我做了什么:我創建了一個邏輯,但它不起作用
it('Form check is valid or not if no values entered', () => {
expect(component.userCreationForm.valid).toBeFalsy();
});
it('Form check is valid or not when values entered', () => {
component.userCreationForm.controls['firstname'].setValue('luther');
component.userCreationForm.controls['lastname'].setValue('adams');
component.userCreationForm.controls['email'].setValue('test@gmail.com');
component.userCreationForm.controls['password'].setValue('123456');
expect(component.userCreationForm.valid).toBeTruthy();
});
it('Form Submitted should check from is submitted', () => {
// check form is invalid
expect(component.userCreationForm.invalid).toBeTruthy();
let btn = fixture.debugElement.query(By.css('button[type=submit]'));
// Check button is disabled
expect(btn.nativeElement.disabled).toBeTruthy();
component.userCreationForm.controls['firstname'].setValue('luther');
component.userCreationForm.controls['lastname'].setValue('adams');
component.userCreationForm.controls['email'].setValue('test@gmail.com');
component.userCreationForm.controls['password'].setValue('testpassword');
fixture.detectChanges();
// check button is enabled
expect(btn.nativeElement.disabled).toBeFalsy();
component.onUserCreation();
fixture.detectChanges();
let success = fixture.debugElement.query(By.css('#success-msg')).nativeElement;
expect(success.textContent).toBe('Bubba');
});
html邏輯
<div class="inv-buttons">
<button mat-raised-button color="primary" [disabled]="userCreationForm.invalid" type="submit">Create User</button>
</div>
下面是我的堆棧閃電戰: https://stackblitz.com/edit/angular-9-material-starter-q9wxvq
您想在哪里單擊您創建的 btn。 像下面這樣使用它:-
btn.nativeElement.click();
我在下面更改了您的測試用例:-
it('Form Submitted should check from is submitted',async () => {
// check form is invalid
expect(component.userCreationForm.invalid).toBeTruthy();
let btn = fixture.debugElement.query(By.css('button[type=submit]'));
// Check button is disabled
expect(btn.nativeElement.disabled).toBeTruthy();
component.userCreationForm.controls['firstname'].setValue('luther');
component.userCreationForm.controls['lastname'].setValue('adams');
component.userCreationForm.controls['email'].setValue('test@gmail.com');
component.userCreationForm.controls['password'].setValue('testpassword');
fixture.detectChanges();
// check button is enabled
expect(btn.nativeElement.disabled).toBeFalsy();
await fixture.whenStable();
console.clear();
btn.nativeElement.click();
fixture.detectChanges();
//component.onUserCreation();
//fixture.detectChanges();
//let success = fixture.debugElement.query(By.css('#success-msg')).nativeElement;
//expect(success.textContent).toBe('Bubba');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.