Angular 2 unit testing - @ViewChild is undefined

前端 未结 5 1045
情歌与酒
情歌与酒 2021-02-06 20:59

I am writing an Angular 2 unit test. I have a @ViewChild subcomponent that I need to recognize after the component initializes. In this case it\'s a Timepicke

5条回答
  •  佛祖请我去吃肉
    2021-02-06 21:48

    If you want to test the main component with a stub child component, you need to add a provider to the stub child component; as explained in the article Angular Unit Testing @ViewChild.

    import { Component } from '@angular/core';
    import { ChildComponent } from './child.component';
    
    @Component({
      selector: 'app-child',
      template: '',
      providers: [
        {
          provide: ChildComponent,
          useClass: ChildStubComponent
        }
      ]
    })
    export class ChildStubComponent {
      updateTimeStamp() {}
    }
    

    Note the providers metadata, to use the class ChildStubComponent when ChildComponent is required.

    You can then create your parent component normally, its child will be created with the type ChildStubComponent.

提交回复
热议问题