Angular 2 unit testing - @ViewChild is undefined

前端 未结 5 954
情歌与酒
情歌与酒 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:44

    I think it should work. Maybe you forgot to import some module in your configuration. Here is the complete code for test:

    import { TestBed, ComponentFixture, async } from '@angular/core/testing';
    
    import { Component, DebugElement } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    
    import { ExampleComponent } from './test.component';
    import { TimepickerModule, TimepickerComponent } from 'ng2-bootstrap/ng2-bootstrap';
    
    describe('Example Test', () => {
      let exampleComponent: ExampleComponent;
      let fixture: ComponentFixture;
    
      beforeEach(() => {
        TestBed.configureTestingModule({
          imports: [FormsModule, TimepickerModule.forRoot()],
          declarations: [
            ExampleComponent
          ]
        });
        fixture = TestBed.createComponent(ExampleComponent);
      });
    
      it('should recognize a timepicker', async(() => {
        fixture.detectChanges();
        const timepickerChild: TimepickerComponent = fixture.componentInstance.timepickerChild;
        console.log('timepickerChild', timepickerChild);
        expect(timepickerChild).toBeDefined();
      }));
    });
    

    Plunker Example

提交回复
热议问题