Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular reactive form test not working when setting value. How to unit test?

I am trying to unit test a simple reactive form in Angular 5, and don't understand why setting the value in a unit test does not work.

I build the form in my ngOnInit, with the formbuilder:

component.ts

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

In my unit test, I have the normal CLI setutp, in befofreEach:

beforeEach(() => {
  fixture = TestBed.createComponent(SignInComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

My unit test then looks like this:

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

}));

I tried printing only

console.log(form.get('email').value)

And then the value is aaa and bbb as expected. I am very confused and hope you can help me understand this.

like image 626
Manish Shrestha Avatar asked Feb 08 '18 10:02

Manish Shrestha


1 Answers

You can have a function defined in the test suite to update the form values:

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

and you can call this function to set values from your test case:

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

Hope this helps.

like image 106
nircraft Avatar answered Oct 09 '22 23:10

nircraft