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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With