【问题标题】:How to unit test ngx-formly?如何对 ngx-formly 进行单元测试?
【发布时间】:2021-10-04 01:54:32
【问题描述】:

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

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

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

文档:

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

});

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

【问题讨论】:

    标签: angular unit-testing validation angular-formly ngx-formly


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2021-01-30
      • 2012-01-08
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-30
      • 2019-01-05
      • 2011-03-16
      相关资源
      最近更新 更多