I am confused with lifecycle hooks in connection with testing Jasmine. LifeCycle Angular does not mention testing https://angular.io/guide/lifecycle-hooks . The test document only mentions OnChange https://angular.io/guide/testing . I have a component sample as follows:
import { Component, OnInit, AfterViewInit, OnDestroy, ElementRef } from '@angular/core'; ... @Component({ selector: 'app-prod-category-detail', templateUrl: './prod-category-detail.component.html', styleUrls: ['./prod-category-detail.component.css'] }) // export class ProdCategoryDetailComponent implements OnInit, AfterViewInit, OnDestroy { ... nav: HTMLSelectElement; // constructor( ... private _elementRef: ElementRef ) { } ... ngAfterViewInit() { console.log( 'ProdCategoryDetailComponent: ngAfterViewInit' ); this.nav = this._elementRef.nativeElement.querySelector('#nav'); } ... }
As a side note, this is an Angular CLI app with the latest downloads. In Karma, I do not see the console log, so nav is never installed. I currently refer to this in my specification as follows:
beforeEach(() => { fixture = TestBed.createComponent(ProdCategoryDetailComponent); sut = fixture.componentInstance; sut.ngAfterViewInit( ); fixture.detectChanges( ); });
Is this the right way to do this?
For shusson, this happens a while ago, and I have not looked at it for a while. Hope this helps. Please note: I am using Primetime library:
describe('ProdCategoryDetailComponent', () => { let sut: ProdCategoryDetailComponent; let fixture: ComponentFixture< ProdCategoryDetailComponent >; let alertService: AlertsService; let prodCatService: ProdCategoryServiceMock; let confirmService: ConfirmationServiceMock; let elementRef: MockElementRef; // beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ FormsModule, ButtonModule, BrowserAnimationsModule ], declarations: [ ProdCategoryDetailComponent, AlertsComponent, ConfirmDialog ], providers: [ AlertsService, { provide: ProdCategoryService, useClass: ProdCategoryServiceMock }, { provide: MockBackend, useClass: MockBackend }, { provide: BaseRequestOptions, useClass: BaseRequestOptions }, { provide: ConfirmationService, useClass: ConfirmationServiceMock }, { provide: ElementRef, useClass: MockElementRef } ] }) .compileComponents(); })); // beforeEach(inject([AlertsService, ProdCategoryService, ConfirmationService, ElementRef], (srvc: AlertsService, pcsm: ProdCategoryServiceMock, cs: ConfirmationServiceMock, er: MockElementRef) => { alertService = srvc; prodCatService = pcsm; confirmService = cs; elementRef = er; })); // beforeEach(() => { fixture = TestBed.createComponent(ProdCategoryDetailComponent); sut = fixture.componentInstance; sut.ngAfterViewInit( ); fixture.detectChanges( ); }); //