l-lin / angular-datatables

DataTables with Angular
https://l-lin.github.io/angular-datatables/
MIT License
1.57k stars 486 forks source link

'TypeError: Cannot read properties of undefined (reading 'dtInstance') in Angular Unit test #1623

Closed beegalayuvraj closed 2 years ago

beegalayuvraj commented 2 years ago

:beetle: bug report

Getting Cannot read properties of undefined (reading 'dtInstance') while writing the angular test case for data table.

spec file:

it('dtInstance', async (done) => { const query = fixture.debugElement.query(By.directive(DataTableDirective)); const dir = query.injector.get(DataTableDirective); expect(dir).toBeTruthy(); const instance:DataTables.Api = await dir.dtInstance; fixture.detectChanges(); expect(instance).toBeTruthy(); done(); });

component file:

@ViewChild(DataTableDirective, { static: false }) dtElement: DataTableDirective;

ngOnInit() { this.dtOptions = { pagingType: 'full_numbers', pageLength: 10, retrieve: true // Fix for the datatables re-initialize }; this.dtTrigger.next(); //data is initialized before this. this.dtElement.dtInstance.then((dtInstance: DataTables.Api) => { // ERROR HERE

 });

}

Issue:

Whenever fixture.detectChanges() is called. its calling the ngOnInit() in which its not able to resolve dtInstance on dtElement

Kindly let me know what am i missing.

shanmukhateja commented 2 years ago

You're using dtElement in ngOnInit. ViewChild elements are available only from ngAfterViewInit.

Move the dtElement code to ngAfterViewInit.

stale[bot] commented 2 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] commented 2 years ago

This issue has been closed due to inactivity. Please feel free to re-open the issue to add new inputs.