我正在使用Jest测试我的组件。当我运行测试时出错。
下面是我的onClickLogin()代码块
onClickLogin() { if(this.loginForm.valid){ this.api.getLoginData().subscribe(res=>{ const user = res.find((a)=>{ return a.email === this.loginForm.value.email && a.password === this.loginForm.value.password }); if(user){ this.toastr.success("Login success!!"); this.loginForm.reset(); this.router.navigate(['dashboard']); } else{ this.toastr.error("Invalid credentials!"); } }, ()=>{ this.toastr.error("Something went wrong!!"); }); } else{ this.toastr.error("Please enter all required fields to proceed!"); } }
我还使用Angular Material UI和表单验证,因此我明确禁用了表单验证。
下面是我使用Jest的测试代码块。
it('should navigate to dashboard on clicking login', waitForAsync( () => { const button = elLogin.queryAll(By.css('button')); loginComponent.loginForm.clearAsyncValidators(); loginComponent.loginForm.clearValidators(); loginComponent.loginForm.updateValueAndValidity(); button[0].nativeElement.click(); loginFixture.whenStable().then(() => { loginFixture.detectChanges(); expect(location.path()).toBe('/dashboard'); }); }));
有什么帮助吗?
我尝试过像这样禁用所有表单验证
loginComponent.loginForm.clearAsyncValidators(); loginComponent.loginForm.clearValidators(); loginComponent.loginForm.updateValueAndValidity();
此外,我还尝试为必填字段设置值
const email = loginComponent.loginForm.controls['email'].setValue("test@gmail.com"); const password = loginComponent.loginForm.controls['password'].setValue("test");
但错误如下
TypeError: Cannot read properties of undefined (reading 'clearAsyncValidators') const button = elLogin.queryAll(By.css('button')); > 93 | loginComponent.loginForm.clearAsyncValidators(); | ^ 94 | loginComponent.loginForm.clearValidators(); 95 | loginComponent.loginForm.updateValueAndValidity(); 96 | button[0].nativeElement.click();
有什么帮助吗?谢谢