【问题标题】:angular reactive form test not working when setting value. How to unit test?设置值时,角度反应形式测试不起作用。如何进行单元测试?
【发布时间】:2018-07-18 20:42:15
【问题描述】:

我正在尝试在 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。 我很困惑,希望你能帮助我理解这一点。

【问题讨论】:

  • 你能在这里详细解释你的问题吗?我可以看到您可以在测试中设置这些值后打印它们。

标签: angular unit-testing angular-reactive-forms


【解决方案1】:

您可以在测试套件中定义一个函数来更新表单值:

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();
}));

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 2018-11-16
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多