作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试在 Angular 5 中对一个简单的响应式表单进行单元测试,但不明白为什么在单元测试中设置值不起作用。
我在 ngOnInit 中使用 formbuilder 构建表单:
ngOnInit() {
this.loginForm = this.fb.group({
email: ['', [Validators.required, ValidateEmail]],
password: ['', Validators.required]
});
}
在我的单元测试中,我有正常的 CLI setutp,在 befofreEach 中:
beforeEach(() => {
fixture = TestBed.createComponent(SignInComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
我的单元测试看起来像这样:
fit('login-form printing unexpected value', fakeAsync(() => {
const form = component.loginForm;
fixture.detectChanges();
tick();
form.controls['email'].setValue('aaa');
console.log(form.get('email')); // PRINTS bbb
fixture.detectChanges();
tick();
form.controls['email'].setValue('bbb');
console.log(form.get('email'));// PRINTS bbb
}));
我只试过打印
console.log(form.get('email').value)
然后该值如预期的那样是 aaa 和 bbb。我很困惑,希望你能帮助我理解这一点。
最佳答案
您可以在测试套件中定义一个函数来更新表单值:
function updateForm(name: string, id: string, comments: string) {
component.myForm.controls['name'].setValue(name);
component.myForm.controls['id'].setValue(id);
component.myForm.controls['comments'].setValue(comments);
}
并且您可以调用此函数来设置测试用例中的值:
it('form value should update from form changes', fakeAsync(() => {
updateForm('Martin K', 'xyzi', 'Test');
expect(component.myForm.value).toEqual(page.validFormValues); // validate against another value.
expect(component.myForm.invalid).toBeTruthy();
}));
希望这对您有所帮助。
关于设置值时 Angular react 形式测试不起作用。如何进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48682770/
我是一名优秀的程序员,十分优秀!