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

我试图用单位测试来测试我的表格字段,但业力表示我的 property 是 undefined . 我在 formGroup 上做了一个控制台日志,它是 undefined . 但是当我控制台记录我的组件时,我得到了所有参数 .

This is my component:

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)]],

This is my Test

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

This is my error

TypeError:无法读取未定义的属性'contains'

回答(2)

2 years ago

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

2 years ago

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

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

在创建组件之后 .

当你没有处于测试模式时,Angular会为你做这件事 .