angular - 如何在组件中测试FormGroupDirective?

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

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

最佳答案

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

像在我的父组件中一样创建了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();
  });
});

关于angular - 如何在组件中测试FormGroupDirective?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53427027/

相关文章:

json - 如何从 package.json 加载 Angular (v4+)应用程序中的版本号?

typescript - 如何更改 TypeScript 中的只读属性?

unit-testing - 您如何使用规范编写参数化测试?

angular - Firebase 单独的 firebase.json 文件用于测试和生产 - 使用 Angular 环境文件变量?

Angular ContentChildren(Component) 获取任何类型

javascript - 过滤Json数组多键

javascript - 用值初始化 Guard

python - pytest 断言用于 pyspark 数据帧比较

javascript - 如何使用 jest-fetch-mock 模拟获取响应

angular - Angular Reactive Form 的深拷贝?