angularunit-testingvalidationangular-formlyngx-formly

How to unit test ngx-formly?


I am trying to unit test ngx formly but I am getting the following error:

[Formly Error] The validator "emailValidator" could not be found. Please make sure that is registered through the FormlyModule declaration.

I also checked the angular formly documentation and they have written the code in the same way.

Documentation:

FIELD WITH CUSTOM VALIDATION
You just need to include the name of the validate function, declared in FormlyModule, within the property validators.validation.

{
  key: 'ip',
  type: 'input',
  templateOptions: {
    label: 'IP Address (using custom validation declared in ngModule)',
    required: true,
  },
  validators: {
    validation: ['ip'],
  },
},

Documentation Link: https://formly.dev/guide/validation


** MY CODE **

form.component.ts:

export class FormComponent {
  fields: FormlyFieldConfig[] = [
    {
      key: 'email',
      type: 'input',
      templateOptions: {
        label: 'Email address',
        placeholder: 'Enter email',
        type: 'email',
        required: true,
        attributes: {
          autocapitalize: 'off',
          autocorrect: 'off',
          autocomplete: 'off',
        },
      },
      validators: {
        validation: ['emailValidator'],
      },
    },
  ];

form.component.spec.ts:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { FormlyModule } from '@ngx-formly/core';
import { FormlyMaterialModule } from '@ngx-formly/material';

import { FormComponent } from './form.component';

describe('FormComponent', () => {
  let component: FormComponent;
  let fixture: ComponentFixture<FormComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ FormComponent],
      imports: [
        FormlyModule.forRoot(),
        FormlyMaterialModule,
        ReactiveFormsModule,
      ]
    })
    .compileComponents();
  });

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

  it('should create', () => {
    expect(component).toBeTruthy();
  });

});

Can someone please guide me? Any leads would be helpful! Thank you!


Solution

  • can you please share your App.module file content? Your "emailValidator" has to be registered in your import section of app.module file in the following way:

    imports: [
    FormlyModule.forRoot({
       validators: [
                    { name: 'emailvalidator', validation: validator_function_name },
                   
                  ]
               )}
    

    please check here https://formly.dev/examples/validation/custom-validation