如何在组件中测试FormGroupDirective?

时间:2018-11-22 08:51:30

标签: angular typescript unit-testing karma-jasmine angular7

我在使用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);
        (...)
      });

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

2 个答案:

答案 0 :(得分:0)

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

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

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

dataSource

在提供程序中添加FormControlDirective至关重要,以避免出现错误没有为FormControlDirective提供程序

CollectionView

答案 1 :(得分:0)

这是我设法解决注入FormGroupDirective问题的方法。

我的伴侣-

import {Component, Input, OnInit} from '@angular/core';
import {ControlContainer, FormControl, FormGroupDirective} from "@angular/forms";

@Component({
  selector: 'app-checkbox',
  templateUrl: './checkbox.component.html',
  styleUrls: ['./checkbox.component.scss'],
  viewProviders: [{provide: ControlContainer, useExisting: FormGroupDirective}]
})
export class CheckboxComponent implements OnInit {

  @Input() controlName: string;
  public formControl: FormControl;

  constructor(private formGroupDirective: FormGroupDirective) {

  }

  ngOnInit(): void {
    this.formControl = this.formGroupDirective.form.get(this.controlName) as FormControl;
  }

}

测试-

import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {CheckboxComponent} from './checkbox.component';
import {FormBuilder, FormGroupDirective, ReactiveFormsModule} from "@angular/forms";

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

  beforeEach(waitForAsync(() => {
    const fb = new FormBuilder()

    const formGroupDirective = new FormGroupDirective([], []);
    formGroupDirective.form = fb.group({
      test: fb.control(null)
    });

    TestBed.configureTestingModule({
      declarations: [CheckboxComponent],
      imports: [
        ReactiveFormsModule
      ],
      providers: [
        FormGroupDirective,
        FormBuilder,
        {provide: FormGroupDirective, useValue: formGroupDirective}
      ]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CheckboxComponent);
    component = fixture.componentInstance;
    component.controlName = 'test';

    fixture.detectChanges();
  });

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