1

我正在尝试正式对 ngx 进行单元测试,但出现以下错误:

[正式错误] 找不到验证器“emailValidator”。请确保通过 FormlyModule 声明进行注册。

我还检查了角度形式的文档,他们以相同的方式编写了代码。

文档:

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'],
  },
},

文档链接:https ://formly.dev/guide/validation


** 我的代码 **

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();
  });

});

有人可以指导我吗?任何线索都会有所帮助!谢谢!

4

1 回答 1

1

你能分享你的 App.module 文件内容吗?您的“emailValidator”必须通过以下方式在 app.module 文件的导入部分中注册:

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

请在此处查看https://formly.dev/examples/validation/custom-validation

于 2021-08-12T12:26:03.050 回答