角单元测试父组件,其子组件为@Input

时间:2020-06-15 10:10:42

标签: angular angular-test

我正尝试测试包含子组件作为@Input的父组件,但是当我尝试执行应创建测试时,我的父组件测试会触发错误。

这是我的父组件代码:

export class ParentComponent implements OnInit  {

@Input() childComponent: ChildComponent;

 mainForm: FormGroup;

 constructor(private readonly fb: FormBuilder) {}

  ngOnInit() {

    this.mainForm = this.fb.group({
      id : [],
      object: ['', [Validators.required , Validators.maxLength(500)]]
    });

    // this line cause the problem in my unit test
    this.childComponent.infoForm.valueChanges.subscribe(data => {
     // some code ...

    });

  }

}

这是我的子组件的代码:

export class ChildComponent implements OnInit {

  infoForm: FormGroup;

  constructor(private readonly fb: FormBuilder) {}

  ngOnInit() {


    this.infoForm = this.fb.group({
      property1: ['' , [Validators.required]],
      property2 : ['' , [Validators.required]],
      property3: ['' , [Validators.required]]

    });

  }
}

这是我对父组件的单元测试:

describe('ParentComponent', () => {
  let component: ParentComponent;
  let fixture: ComponentFixture<ParentComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ParentComponent , ChildComponent ] ,
      imports: [
        SharedModule ,
        NoopAnimationsModule ,
        HttpClientTestingModule
      ],
      providers: [
        DemandeService
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {

    fixture = TestBed.createComponent(ParentComponent);
    component = fixture.componentInstance;

    fixture.detectChanges();
  });


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

});

但是当我运行测试时,出现此错误:

TypeError: Cannot read property 'infoForm' of undefined

我认为我的childComponent在我的测试中未定义。

能帮我解决这个问题吗?

谢谢。

致谢!

0 个答案:

没有答案