gpt4 book ai didi

Angular - 测试在表单验证时显示错误

转载 作者:行者123 更新时间:2023-12-05 02:55:44 25 4
gpt4 key购买 nike

我有一个看起来像这样的测试:

...
component.registerForm.controls['username'].setValue('VALID USERNAME');

fixture.detectChanges();

expect(component.registerForm.valid).toEqual(true); // FIRST ASSERTION
const errors = fixture.debugElement.queryAll(By.css('.error.username'));
expect(errors.length).toBe(0); // <-- SECOND ASSERTION: IT VAILS HERE!!!

问题在于,即使表单有效并且第一个断言通过,第二个断言也会失败,因为会显示“required”错误消息。在我看来,表单似乎已更新,而 fixture.debugElement 并未更新,因此它会显示初始错误。 IE。它忽略设置 username 值。

更新:我有非常相似的问题并且相信来源可能是相同的:我有一些测试用例我想确保我的表单验证设置正确(即有效案例导致有效形式,无效案例导致无效形式)(我将表单简化为 username only):

getUsernameCases().forEach((testCase) => {
it(`should be valid: ${testCase.valid}`, () => {
component.myForm.get('username').setValue(testCase.username);

component.registerForm.updateValueAndValidity();
fixture.detectChanges();
component.registerForm.updateValueAndValidity(); // Second time to make sure order does not matter

expect(component.myForm.valid).toBe(testCase.valid); // ALWAYS INVALID HERE
});
});

问题是无论值如何,表单总是无效的。它有 required 错误 - 这意味着显示的是初始状态。在 setValue 之前。

最佳答案

这在很大程度上取决于您构建表单的方式,但我可以编写一个测试,以我认为您正在尝试的方式断言表单的有效性。我需要查看被测组件才能确定。

Here is a stackblitz showing these tests .

应用程序组件.ts:

export class AppComponent implements OnInit {

myForm: FormGroup;

//Helper to get the username control to check error state
get username() {
return this.myForm.get('username');
}

constructor(private fb: FormBuilder) {
}

ngOnInit() {
//"Username" has two validations to test: required and minLength
this.myForm = this.fb.group({
'username': new FormControl(null, [Validators.required, Validators.minLength(10)])
});
}
}

应用程序组件.html:

<form [formGroup]="myForm">
<!-- "username" input with conditional styles based on error state -->
<input type="text"
formControlName="username"
[class.username-valid]="!username.errors"
[class.error-username-required]="username.errors?.required"
[class.error-username-minlength]="username.errors?.minlength">
</form>

app.component.spec.ts:

describe('AppComponent', () => {
let fixture: ComponentFixture<AppComponent>;
let component: AppComponent;

beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
FormsModule,
ReactiveFormsModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));

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

describe('The form validity', () => {
const testCases = [
{
expected: true,
username: 'VALID_USERNAME',
expectedCss: 'username-valid'
},
{
expected: false,
username: null,
expectedCss: 'error-username-required'
},
{
expected: false,
username: 'too_short',
expectedCss: 'error-username-minlength'
}
];

testCases.forEach(testCase => {
it(`should update the form validity: ${testCase.expected}`, () => {
component.myForm.get('username').setValue(testCase.username);
component.myForm.updateValueAndValidity();
fixture.detectChanges();
expect(component.myForm.valid).toBe(testCase.expected); //assert the form is valid/invalid
expect(fixture.debugElement.query(By.css(`.${testCase.expectedCss}`))).toBeTruthy(); //assert the conditional style is applied
});
});
});
});

关于Angular - 测试在表单验证时显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61034435/

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