如何对 ngx 进行单元测试?

时间:2021-07-28 10:12:15

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

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

<块引用>

[Formly Error] 无法找到验证器“emailValidator”。 请确保通过 FormlyModule 注册 声明。

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

文档:

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

});

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

0 个答案:

没有答案