I've implemented a component as shown below:
<select #tabSelect (change)="tabLoad($event.target.value)" class="mr-2">
<option value="tab1">First tab</option>
<option value="tab2">Second tab</option>
</select>
<div class="tab-content">
<div class="tab-pane fade show active">
<ng-template #tabContent></ng-template>
</div>
</div>
The component has two tabs which trigger the tabLoad() function and pass along the clicked tab as a parameter.
export class DemoComponent implements OnInit {
@ViewChild('tabContent', { read: ViewContainerRef }) entry: ViewContainerRef;
activeTab: any = 'tab1';
constructor(private resolver: ComponentFactoryResolver) { }
ngOnInit() {
this.tabLoad(this.activeTab);
}
tabLoad(page) {
setTimeout(() => {
this.activeTab = page;
this.entry.clear();
if (page == 'tab1') {
const factory = this.resolver.resolveComponentFactory(Tab1Component);
console.log(this.entry);
this.entry.createComponent(factory);
} else if (page == 'tab2') {
const factory = this.resolver.resolveComponentFactory(Tab2Component);
this.entry.createComponent(factory);
}
}, 500);
}
}
In this .ts file, I defined a variable called entry that refers to #tabContent. The tab content loads a component based on the active page.
I wrote a test suite for this functionality as follows:
fdescribe('DemoComponent', () => {
let component: DemoComponent;
let fixture: ComponentFixture<DemoComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [RouterModule.forRoot([]), SharedModule],
declarations: [Tab1Component, Tab2Component],
}).compileComponents().then(() => {
fixture = TestBed.createComponent(DemoComponent);
component = fixture.componentInstance;
});
}));
it('should set activeTab correctly and clear entry when tabLoad is called', fakeAsync(() => {
component.tabLoad("tab1");
flush();
expect(component.activeTab).toBe('tab1');
}));
});
This test fails with an error stating
Cannot read property 'clear' of undefined
when calling this.entry.clear();. Additionally, console.log(this.entry);
prints undefined.
I attempted to add fixture.detectChanges()
within the scope of .compileComponents().then(() => {})
, but the issue persists. However, everything works fine when I navigate to the page after serving it using ng serve.