【发布时间】:2019-03-13 16:57:32
【问题描述】:
我正在尝试在响应式表单上测试自定义验证字段的有效状态。
我的组件如下:
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 组件进行了如下设置的测试,我在其中设置了年龄字段的值,然后测试它是否有效 - 测试返回有效性为 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 函数以某种方式连接到测试组件,但我无法弄清楚如何 - 谁能建议我可以做到这一点的方法(如果可能的话)?
最终,我正在尝试测试表单的有效性,以确保在所有必填字段都有效时可以提交它。
【问题讨论】:
标签: javascript angular unit-testing testing