8

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.

1
  • Can you explain your problem in details here? I can see that you are able to print the values after setting them up in your test. Commented Nov 5, 2018 at 22:15

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.