【问题标题】:How to mock a FormBuilder for Angular Component Unit Test如何为 Angular 组件单元测试模拟 FormBuilder
【发布时间】:2020-06-19 09:00:20
【问题描述】:

我在一个 Angular 9 项目中工作。

我有一个组件接受 formBuilder 作为来自父组件的输入。 这是我的子组件(我正在测试的那个):

export class ChildComponent implements OnInit {
  @Input() parentForm: FormGroup;  //this is coming from the parentComponent

  ngOnInit(): void {
    if (this.parentForm) {
      this.filteredSelectables = this.parentForm
        .get("recipientTypes")
        ...
    }
  }
...

我想为这个组件编写测试,但是我需要创建一个测试可以使用的表单(或者我需要模拟父组件并返回我想要的表单?)

我已将 FormBuilder 添加到 testBed 提供程序,但我仍然不知道如何制作可以用来测试的模拟表单。 “应该创建”测试正在通过,但我无法测试其他任何东西,因为 parentForm 不能为它们为空。这是我目前的测试:

describe("ChildComponent", () => {
  let component: ChildComponent;
  let fixture: ComponentFixture<ChildComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ChildComponent, MatAutocomplete],
      providers: [FormBuilder],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(ChildComponent);
        component = fixture.componentInstance;
      });
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ChildComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

我尝试过这样创建表单:

component.parentForm = FormBuilder.group({
      recipientTypes: new FormControl(
        {
          value: ["mock"],
          disabled: true
        },
        Validators.required
      )
    });

并将其添加到 beforeEach() 甚至在实际测试中。但我出错了。

我想也许我需要模拟 parentComponent 并让它发送一个 formBuilder? 这是我的父组件:

export class ParentComponent implements OnInit, OnDestroy {
  parentForm: FormGroup;

  constructor(
    private router: Router,
    private formBuilder: FormBuilder
  ) {}

  ngOnInit() {
    this.setFormTemplate();
  }

  setFormTemplate() {
    this.templateForm = this.formBuilder.group({
      name: new FormControl(
        {
          value: this.name,
          disabled: true
        },
        Validators.required
      ),
      recipientTypes: new FormControl(
        {
          value: this.recipientTypes,
          disabled: true
        },
        Validators.required
      )
    });
  }
...

如何为我的测试制作一个 formBuilder?

【问题讨论】:

  • 你得到什么错误?
  • 我得到:Property 'group' does not exist on type 'typeof FormBuilder,如果我只使用FormBuilder.group。如果我尝试component.formBuilder 它不起作用,因为组件实际上没有formBuilder,父组件有。我错了:Property 'formBuilder' does not exist on type 'ChipsAutocompleteInputComponent'.

标签: angular testing angular-reactive-forms formbuilder angular9


【解决方案1】:

试试吧!

import { FormBuilder } from '@angular/forms';
....
describe("ChildComponent", () => {
  let component: ChildComponent;
  let fixture: ComponentFixture<ChildComponent>;
  let formBuilder: FormBuilder;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ChildComponent, MatAutocomplete],
      providers: [FormBuilder], // add this as a provider
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(ChildComponent);
        component = fixture.componentInstance;
      });
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ChildComponent);
    component = fixture.componentInstance;
    formBuilder = TestBed.inject(FormBuilder); // get a handle on formBuilder
    // add the mock data here
    component.parentForm = formBuilder.group({ 
      recipientTypes: new FormControl(
        {
          value: ["mock"],
          disabled: true
        },
        Validators.required
      )
    });
    // this fixture.detectChanges will kick off the ngOnInit
    fixture.detectChanges();
  });

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

【讨论】:

  • 我得到错误:“当我尝试这个时,“类型'typeof FormBuilder'上不存在属性'组'。
  • 尝试我对注入FormBuilder 并使用injection 来创建formBuilder 的编辑。
  • 注入成功,我现在可以使用 formBuilder。非常感谢,我真的很感激!
猜你喜欢
  • 2016-11-23
  • 1970-01-01
  • 1970-01-01
  • 2018-11-24
  • 2020-04-19
  • 2020-04-05
  • 1970-01-01
  • 1970-01-01
  • 2023-02-17
相关资源
最近更新 更多