如何在单元测试中解决 formgroup 中的 TypeError Angular

How to resolve TypeError in formgroup in Unit Testing Angular

我正在尝试使用单元测试来测试 angular 中的表单字段,但 karma 说我的 属性 是 undefined。我在 formGroup 上做了一个控制台日志,它是 undefined。但是当我控制台记录我的组件时,我得到了所有参数。

这是我的组件:

constructor(
  private _fb: FormBuilder,
  private donationService: DonationService,
  private formValidationMessages: ValidationserviceService,
  private ziptoLocationService: ZiptolocationService,
  private http: HttpClient,
  private snack: MatSnackBar,
  private cd: ChangeDetectorRef,
  private nservice: NService) { }

ngOnInit() {
  this.donationForm = this._fb.group({
  gross_gift_amount: ['', [Validators.required, Validators.pattern('^[0-9]+([.][0-9]{1,2})?$')]],
  billing_first_name: ['', [Validators.required, Validators.minLength(3)]],
  billing_last_name: ['', [Validators.required, Validators.maxLength(50)]],

这是我的测试

import { FormBuilder } from '@angular/forms';
import { DonationComponent } from './donation.component';

describe('Donation Form', () => {
  let component: DonationComponent;

beforeEach(() => {
      component = new DonationComponent( new FormBuilder(), null, null, null, null, null, null, null );
  });

it('should create a form with 10 controls', () => {
      expect(component.donationForm.contains('gross_gift_amount')).toBeTruthy();
  });
});

这是我的错误

TypeError: Cannot read property 'contains' of undefined

您的 donationForm 属性 未初始化,因为您的组件的 ngOnOnit() 方法从未在您的测试中调用。

尝试在 beforeEach 中调用方法 ngOnInit,如下所示:

beforeEach(() => {
    component = new DonationComponent( new FormBuilder(), null, null, null, null, null, null, null );
    component.ngOnInit();
});

就在创建组件之后。

Angular 会在您不处于测试模式时为您完成。