Testing custom async validator

Discussão em 'Angular' iniciado por Pablo52, Janeiro 20, 2025.

  1. Pablo52

    Pablo52 Guest

    I'm trying to test that my form control is invalid when my mock custom async validator returns a key value pair.

    This is the mock validator I have created:

    export async function mockUniqueEmailValidatorFn(control: AbstractControl) {
    const existingEmailAddresses = ['TestEmail@gmail.com'];
    if(existingEmailAddresses.includes(control.value)) {
    return of({'emailUniquenessViolated': true})
    .pipe(
    first()
    );
    } else {
    return of(null);
    }


    This is the unit test I have setup:

    it('should be invalid when email has already been used to create an account', () => {
    //Arrange
    component.registerForm.controls['email'].clearAsyncValidators;
    component.registerForm.controls['email'].addAsyncValidators(mockUniqueEmailValidatorFn);
    //Act
    component.registerForm.controls['email'].setValue("TestEmail@gmail.com");
    fixture.detectChanges();
    console.log(component.registerForm.controls['email']);

    //Assert
    expect(component.registerForm.controls['email'].invalid).toBeTruthy();
    });


    The test is failing as the invalid property on the email form control is false. Any ideas why this is happening?

    A few odd things I have noticed. The form control is both not valid and not invalid at the time of me logging the control to the console:

    [​IMG]

    Also, the status of the form control is "PENDING" at the time of the logging the form control to the console, even though I have used the first() rxjs operator which should complete the observable once it emits it's first value:

    [​IMG]

    Continue reading...

Compartilhe esta Página