gpt4 book ai didi

设置值时 Angular react 形式测试不起作用。如何进行单元测试?

转载 作者:太空狗 更新时间:2023-10-29 17:40:22 27 4
gpt4 key购买 nike

我正在尝试在 Angular 5 中对一个简单的响应式表单进行单元测试,但不明白为什么在单元测试中设置值不起作用。

我在 ngOnInit 中使用 formbuilder 构建表单:

组件.ts

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/

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