如何在组件中测试FormGroupDirective?

问题描述 投票:6回答:1

我在用FormGroupDirective中的viewProviders测试组件时遇到了一些问题。无法创建parent的模拟并设置空的formGroup。

我的组件:

@Component({
   (...)
   viewProviders: [
      {
        provide: ControlContainer, useExisting: FormGroupDirective
      }
    ]
  })
export class SomeNestedFormComponent implements OnInit {
  form: FormGroup;

  constructor(private fb: FormBuilder, private parent: FormGroupDirective) {}

  ngOnInit() {
    this.form = this.parent.form;
    this.form.addControl('field', this.createSomeFormGroup());
  }
}

规格:

describe('SomeNestedFormComponent', () => {
  let component: SomeNestedFormComponent;
  let fixture: ComponentFixture<SomeNestedFormComponent>;
  let formGroupDirective: Partial<FormGroupDirective>;

  beforeEach(async(() => {
    formGroupDirective = {
      form: new FormGroup({})
    };

    TestBed.configureTestingModule({
      imports: [
        SharedModule,
        FormsModule,
        ReactiveFormsModule
      ],
      declarations: [SomeNestedFormComponent],
      providers: []
    })
      .overrideComponent(PermissionListComponent, {
        set: {
          viewProviders: [
            {
              provide: FormGroupDirective, useValue: formGroupDirective
            }
          ]
        }
      })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(SomeNestedFormComponent);
        component = fixture.componentInstance;
        component.ngOnInit();
        fixture.detectChanges();
      });
  }));

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

此抛出:Error: formGroupName must be used with a parent formGroup directive. (...)尝试将FormGroupDirective作为服务与spyOn一起处理,但是会抛出TypeError: this.form.addControl is not a function

describe('SomeNestedFormComponent', () => {
  (...)
  let fgdSpy:  jasmine.SpyObj<SomeNestedFormComponent>;

  beforeEach(async(() => {
    const FGDirectiveSpy = jasmine.createSpyObj('FormGroupDirective', ['form', 'addControl']);

    TestBed.configureTestingModule({
      (...)
      providers: [
        {provide: FormGroupDirective, useValue: FGDirectiveSpy}
      ]
    })
      .compileComponents()
      .then(() => {
        fgdSpy = TestBed.get(FormGroupDirective);
        (...)
      });

有什么方法可以测试该组件?

angular typescript unit-testing karma-jasmine angular7
1个回答
0
投票

让我分享我在这个场景中所做的事情。

像在我的父组件中一样创建了mockFormGroup,然后将模拟FormControlDirective创建为要在useValue提供程序中使用的formGroupDirective。

最后将父组件的表单分配给如下所示的模拟formGroup

component.parent.form = mockFormGroup;

必不可少的是在提供程序中添加FormControlDirective以避免错误FormControlDirective的没有提供程序

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, NO_ERRORS_SCHEMA } from '@angular/core';
import { ReactiveFormsModule, FormGroupDirective, FormControlDirective, FormBuilder, ControlContainer, FormGroup, FormControl } from '@angular/forms';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

describe('MyComponent', () => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;
  let formGroupDirective: FormControlDirective;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MyComponent ],
      imports: [
        HttpClientTestingModule,
        ReactiveFormsModule
      ],
      providers: [ FormGroupDirective,
        { provide: ControlContainer, useValue: formGroupDirective }
      ],
      schemas: [NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;

    //mock parent formGroup
    const mockFormGroup: FormGroup = new FormGroup({
    });

    //dummy formgroupDirective to avoid undefined addControl function
    const formGroupDirective: FormGroupDirective = new FormGroupDirective([], []);
    
    component.parent.form = mockFormGroup;
    component.ngOnInit();
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });
});
© www.soinside.com 2019 - 2024. All rights reserved.