'How to call onGridReady from Angular Unit Test in order to test the statements init

how i can call the onGridReady function to run unit test on the statement inside the function. My code base look something like below:

GridComponent.ts

export class GridComponent impletes Oninit{
    constructor(serviceObj: ServiceClass) {
        this.summaryData = {};
        this.gridApi =

        this.gridOptions = {
            columnDef: [
                {field: 'name', headerName: 'Name'},
                {fiedld: 'dob', headerName: "Date of Birth"},
                {fiedld: 'title', headerName: "Title"},
                {fiedld: 'salary', headerName: "Salary"},
            ]
        }
    }

    ngOnInit():void {

    }

    onGridReady(params: any) {
        this.gridApi = params.api;
        this.serviceObj.getDetails().subscribe((data: ModalClass[]) => {
            if(data.length > 0) {
                this.summaryData = data;
            } else {
                this.snackBar.open('No Records found.', dismiss);
            }
        },
        (error: any) => {
            this.snackBar.open('Error Occured', 'Dismiss');
        }
        )
    }

}

GridComponent.html

<ag-grid-angular

    style="width:100%;height:calc(82VH)
    class="ag-theme-material"
    [animateRows]="true"
    [rowData] = "summaryData"
    [gridOptions] = 'gridOptions'
></ag-grid-angular>

ServiceClass.ts

export ServiceClass {
    public getDetails():any {
        return this.http.get<ModalClass[]>(url, {withCredentials: true})
    }
}

i have already wrote the test cases for ServiceClass.ts but not able to write the test cases for the statements and branches written inside onGridReady function. Please help.

Thanks in advance.



Solution 1:[1]

Try this:

    it('test with data', () => {
        // declarations
        const mockData = [{id: 1}]
        spyOn(service, 'getDetails').and.returnValue(of(mockData))
        const spySnackBar = spyOn(component.snackBar, 'open')
        const params = { api: 'mock' };
        
        // call
        component.onGridReady(params)

        // expects
        expect(component.summaryData).toEqual(mockData)
        expect(component.gridApi).toEqual(params.api)
        expect(spySnackBar).not.toHaveBeenCalled()
    })


    it('test without data', () => {
        // declarations
        const mockData = []
        spyOn(service, 'getDetails').and.returnValue(of(mockData))
        const spySnackBar = spyOn(component.snackBar, 'open')
        const params = { api: 'mock' };
        
        // call
        component.onGridReady(params)

        // expects
        expect(component.summaryData).not.toEqual(mockData)
        expect(component.gridApi).toEqual(params.api)
        expect(spySnackBar).toHaveBeenCalled()
    })

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1