I have a test that looks like this:
...
component.registerForm.controls['username'].setValue('VALID USERNAME');
fixture.detectChanges();
expect(component.registerForm.valid).toEqual(true); // FIRST ASSERTION
const errors = fixture.debugElement.queryAll(By.css('.error.username'));
expect(errors.length).toBe(0); // <-- SECOND ASSERTION: IT VAILS HERE!!!
The problem is that even if form is valid and the first assertion passes the second assertion fails because "required" error message is displayed. To me it looks as if the form were updated while fixture.debugElement
not so that it displays the initial error. I.e. it ignores setting username
value.
UPDATED:
I have very similar problem and believe that the source might be the same: I have some test cases I would like to make sure that my form validation is set up correctly (i.e. valid cases result in valid form, invalid cases in invalid form) (I simplified the form to username
only):
getUsernameCases().forEach((testCase) => {
it(`should be valid: ${testCase.valid}`, () => {
component.myForm.get('username').setValue(testCase.username);
component.registerForm.updateValueAndValidity();
fixture.detectChanges();
component.registerForm.updateValueAndValidity(); // Second time to make sure order does not matter
expect(component.myForm.valid).toBe(testCase.valid); // ALWAYS INVALID HERE
});
});
The problem is that the form is always invalid regardless of value. It has required
error - it means that is shows form initial state. Before setValue
.