【发布时间】:2017-06-27 21:11:04
【问题描述】:
我正在学习 Angular 2 和使用 @angular/cli 1.0.0-beta.30 进行单元测试,并在测试表单字段有效性的一个方面取得了一些成功,但不是全部。我暂时在我的组件中使用内联模板来消除一层复杂性(单独文件中的表单模板引入了异步性,对吗?)。
ngOnInit() 定义了一个 name 属性,其中包括“required”和“minLength”的验证器。目前,一个空的表单域将正确触发“required”验证器,但不会触发“minLength”验证器。测试中的name.errors数组根本不包含任何对required的引用,name.errors['minLength']返回undefined。 minLength 是否需要异步处理?我无法找到适合我的问题的文档或示例。
// signup-form.component.ts
...
export class SignupFormComponent implements OnInit {
user: FormGroup;
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.user = this.fb.group({
name: ['', [Validators.required, Validators.minLength(2)]],
account: this.fb.group({
email: ['', Validators.required, Validators.pattern("[^ @]*@[^ @]*")],
confirm: ['', Validators.required]
})
})
}
onSubmit({ value, valid }: { value: User, valid: boolean }) {
console.log(value, valid);
}
}
我的测试
// signup-form.component.spec.ts
import { SignupFormComponent } from './signup-form.component';
describe('SignupFormComponent', () => {
let component: SignupFormComponent;
let fixture: ComponentFixture<SignupFormComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [SignupFormComponent],
imports: [
ReactiveFormsModule,
FormsModule
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SignupFormComponent);
component = fixture.componentInstance;
component.ngOnInit();
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('form invalid when empty', () => {
expect(component.user.valid).toBeFalsy();
});
it('name field validity', () => {
let name = component.user.controls['name'];
expect(name.valid).toBeFalsy();
let errors = {};
name.setValue("");
errors = name.errors || {};
expect(errors['required']).toBeTruthy(); // this works
expect(errors['minLength']).toBeTruthy(); // this fails, "undefined"
});
});
【问题讨论】:
标签: javascript forms validation unit-testing angular