Подтвердить что ты не робот

Angular 2 единицы тестирования - @ViewChild undefined

Я пишу Angular 2 unit test. У меня есть подкомпонент @ViewChild, который мне нужно распознать после инициализации компонента. В этом случае это компонент Timepicker из библиотеки ng2-bootstrap, хотя специфика не должна иметь значения. После я detectChanges() экземпляр подкомпонента по-прежнему undefined.

Псевдо-код:

@Component({
    template: `
        <form>
            <timepicker
                #timepickerChild
                [(ngModel)]="myDate">
            </timepicker>
        </form>
    `
})
export class ExampleComponent implements OnInit {
    @ViewChild('timepickerChild') timepickerChild: TimepickerComponent;
    public myDate = new Date();
}


// Spec
describe('Example Test', () => {
    let exampleComponent: ExampleComponent;
    let fixture: ComponentFixture<ExampleComponent>;

    beforeEach(() => {
        TestBed.configureTestingModel({
            // ... whatever needs to be configured
        });
        fixture = TestBed.createComponent(ExampleComponent);
    });

    it('should recognize a timepicker'. async(() => {
        fixture.detectChanges();
        const timepickerChild: Timepicker = fixture.componentInstance.timepickerChild;
        console.log('timepickerChild', timepickerChild)
    }));
});

Псевдокод работает так, как ожидается, пока не дойдете до консольного журнала. timepickerChild - undefined. Почему это происходит?

4b9b3361

Ответ 1

Я думаю, что это должно работать. Может быть, вы забыли импортировать какой-то модуль в вашей конфигурации. Вот полный код для теста:

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<ExampleComponent>;

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

Пример плунжера

Ответ 2

В большинстве случаев просто добавляйте его к замедлению, и вам хорошо идти.

beforeEach(async(() => {
        TestBed
            .configureTestingModule({
                imports: [],
                declarations: [TimepickerComponent],
                providers: [],
            })
            .compileComponents() 

Ответ 3

Убедитесь, что ваш дочерний компонент не имеет * ngIf, который оценивается как false. Если это так, то дочерний компонент будет неопределенным.

Ответ 4

Если вы хотите протестировать основной компонент с дочерним компонентом-заглушкой, вам нужно добавить провайдера в дочерний компонент-заглушку; как описано в статье Угловое модульное тестирование @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() {}
}

Обратите внимание на метаданные поставщиков, чтобы использовать класс ChildStubComponent, когда требуется ChildComponent.

Затем вы можете создать свой родительский компонент в обычном режиме, его дочерний элемент будет создан с типом ChildStubComponent.