gpt4 book ai didi

angular - 如何测试该组件模板包含 mat-error

转载 作者:行者123 更新时间:2023-12-03 23:50:57 25 4
gpt4 key购买 nike

我想为检查显示 mat-error 的组件创建测试。

我创建了一个测试,但它失败了,因为 DOM 在测试期间根本没有 mat-error。尽管在提供项目时它工作正常。

模板片段

<mat-error>
Error message
</mat-error>

测试设置
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
MatFormFieldModule,
ReactiveFormsModule,
MatInputModule,
MatFormFieldModule,
BrowserAnimationsModule
],
declarations: [MyComponent]
}).compileComponents();
}));

beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

fit('should display error', () => {
const matErrorEl: HTMLElement =
fixture.debugElement.query(By.directive(MatError)).nativeElement;
expect(matErrorEl).toBeTruthy();
});
});

最佳答案

tldr;在显示任何错误之前,您必须触摸 FormControl

您必须先触摸组件。
使用 react 形式(其中 nameFormControlFormControl 类型):

component.nameFormControl.markAsTouched();

您的 mat-error 元素现在将显示在 View 中。

对于实际情况,您将在 ngIf 元素上有一个 mat-error 并且还需要设置该错误。

示例模板:

<mat-error *ngIf="nameFormControl.hasError('required')">
Error message
</mat-error>

添加错误:
component.nameFormControl.setErrors({ required: true} as ValidationErrors);

这个问题的类似问题:
How to catch the <mat-error> error message text content using Protractor

关于 Angular 表单验证的官方文档:
https://angular.io/guide/form-validation#why-check-dirty-and-touched

关于angular - 如何测试该组件模板包含 mat-error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57988530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com