如何在组件中测试 FormGroupDirective?

Bla*_*456 9 unit-testing typescript karma-jasmine angular angular7

我在用FormGroupDirectivein测试组件时遇到了一些问题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());
  }
}
Run Code Online (Sandbox Code Playgroud)

规格:

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();
  });
});
Run Code Online (Sandbox Code Playgroud)

此抛出:Error: formGroupName must be used with a parent formGroup directive. (...) 尝试使用 来FormGroupDirective作为服务处理spyOn,但它抛出TypeError: this.form.addControl is not a function

@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());
  }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法测试该组件?

小智 9

以下是我如何设法解决注入 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;
  }

}
Run Code Online (Sandbox Code Playgroud)

考试 -

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();
  });
});
Run Code Online (Sandbox Code Playgroud)


Hel*_*rld 3

让我分享一下我在这个场景中做了什么。

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

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

component.parent.form = mockFormGroup;
Run Code Online (Sandbox Code Playgroud)

必须在提供程序中添加 FormControlDirective 以避免错误No provider for FormControlDirective

component.parent.form = mockFormGroup;
Run Code Online (Sandbox Code Playgroud)