I'm finding it difficult to understand how lifecycle hooks relate to Jasmine testing. The Angular LifeCycle documentation doesn't cover testing at https://angular.io/guide/lifecycle-hooks, while the testing documentation only mentions OnChange at https://angular.io/guide/testing. I have a sample component structured 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');
}
...
}
It's worth noting that this is an Angular CLI application with the latest updates. However, in Karma, I don't see the console log, which means the nav property is never set. Currently, I'm calling it in my spec like so:
beforeEach(() => {
fixture = TestBed.createComponent(ProdCategoryDetailComponent);
sut = fixture.componentInstance;
sut.ngAfterViewInit();
fixture.detectChanges();
});
Is this the correct approach?
This issue dates back quite some time, and I haven't revisited it recently. Hopefully, it provides some insight. Please note that I am using the PrimeFaces PrimeNG 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();
});
//