设置值时,角电抗形式测试不起作用。如何进行单元测试?

Man*_*tha 5 unit-testing angular angular-reactive-forms

我正在尝试在Angular 5中对简单的反应形式进行单元测试,并且不明白为什么在单元测试中设置值不起作用。

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

component.ts

ngOnInit() {
  this.loginForm = this.fb.group({
    email: ['', [Validators.required, ValidateEmail]],
    password: ['', Validators.required]
  });
}
Run Code Online (Sandbox Code Playgroud)

在单元测试中,我在befofreEach中具有正常的CLI setutp:

beforeEach(() => {
  fixture = TestBed.createComponent(SignInComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});
Run Code Online (Sandbox Code Playgroud)

我的单元测试如下:

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

}));
Run Code Online (Sandbox Code Playgroud)

我只尝试打印

console.log(form.get('email').value)
Run Code Online (Sandbox Code Playgroud)

然后值是预期的aaa和bbb。我很困惑,希望您能帮助我理解这一点。

nir*_*aft 3

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

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);
}
Run Code Online (Sandbox Code Playgroud)

您可以调用此函数来设置测试用例中的值:

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();
}));
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。