gpt4 book ai didi

javascript - 在 Angular 中测试具有自定义验证器的响应式(Reactive)表单字段

转载 作者:行者123 更新时间:2023-11-28 20:48:49 25 4
gpt4 key购买 nike

我正在尝试测试响应式表单上自定义验证字段的有效状态。

我的组件如下:

import { Component } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { ageRangeValidator } from './age-range-validator.directive';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Reactive Forms';
genders = ['Female', 'Male'];

constructor(private fb: FormBuilder) { }

userForm = this.fb.group({
firstname: ['', [Validators.required, Validators.minLength(2)]],
surname: ['', [Validators.required, Validators.minLength(2)]],
address: this.fb.group({
houseNo: [''],
street: [''],
city: [''],
postcode: ['']
}),
// Section 1
// age: [null, Validators.min(18)],
// Section 2 - using a Custom validator
age: [null, ageRangeValidator(18, 68)],
gender: ['']
});
}

ageRangeValidator 函数如下 - 这已经过全面测试并且有效:

import { AbstractControl, ValidatorFn } from '@angular/forms';

export function ageRangeValidator(min: number, max: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
if ((!isNaN(control.value) && control.value) && control.value > min && control.value < max) {
return { 'ageRange': true };
}
return null;
};
}

我有一个 App 组件测试,设置如下,我设置了 age 字段的值,然后测试它是否有效 - 测试返回有效性为 false:

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { ReactiveFormsModule } from '@angular/forms';
import { DebugElement } from '@angular/core';

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


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

}));

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

describe(`Test the validity of the fields`, () => {
it(`should return true if a value of 18 or more AND 68 or LESS is supplied (as string or number)`, () => {
const age = app.userForm.controls['age'];
age.setValue(42);
expect(age.valid).toBeTruthy();
});
});

我希望该解决方案需要 ageRangeValidator 函数以某种方式连接到测试组件,但我无法弄清楚如何 - 任何人都可以建议我可以这样做的方法(如果可能的话) )?

最终,我试图测试表单的有效性,以确保在所有必填字段都有效时可以提交表单。

最佳答案

  1. 使用 controls.get('age') 尽量避免直接访问控件
  2. 你需要https://angular.io/api/core/testing/tick设置值后运行验证过程

关于javascript - 在 Angular 中测试具有自定义验证器的响应式(Reactive)表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55147403/

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