ag-Grid: What is the best way to retrieve the gridApi in a Unit Test scenario?

In my testing, I need to unit test a function that relies on the gridApi, such as this.gridApi.getSelectedRows();. However, when the unit test encounters this line, it throws an error:

Failed: Cannot read property 'getSelectedRows' of undefined
, because gridApi has not been defined yet.

How can I properly define the gridApi within a unit test? Typically, the gridApi is initialized in the onGridReady function like so:

onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
    this.gridApi.sizeColumnsToFit();
}

Is there a way to trigger the onGridReady function from a unit test? I'm unsure about what parameters should be passed to it. Alternatively, is there another method to define this.gridApi instead?

Answer №1

In test cases, the initialization of this.gridApi and this.gridColumnApi is done automatically. To achieve this, import AgGridModule from 'ag-grid-angular' is required. Also, initialize the component using the following code:

let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        imports: [
            AgGridModule.withComponents([])
        ]
    }).compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
}));

To test onGridReady, include the following import statement at the top of the file:

import { GridOptions } from "ag-grid-community";

Declare a variable as follows:

gridOptions: GridOptions = <GridOptions>{};

Write the test case:

it('onGridReady called', () => {
const data = {
    api: component.gridOptions.api,
    columnApi: component.gridOptions.columnApi
}
component.onGridReady(params);
expect(component.gridApi).not.toBeNull();
expect(component.gridColumnApi).not.toBeNull();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for managing exceptions in Redux when handling HTTP requests

Currently, I am in the process of learning react alongside redux and redux-observable. My main focus at the moment is on understanding how to handle errors effectively. Here's what I have done so far: I successfully created a redux-observable epic t ...

Testing a function in Angular using Karma and Jasmine

I am facing an issue while testing a method in Angular using Jasmine/Karma. The error message I keep encountering is: TypeError: undefined is not iterable (cannot read property Symbol (Symbol.iterator)) This is how I created the method: myMethod(l ...

What steps should be taken to guarantee that the view is created only after receiving values from the route params subscription?

How can I ensure that the View is only rendered after the subscription has received values? When clicking on the Edit button in MyComponent_1, Angular navigates to MyComponent_2. In MyComponent_2, the view contains a form whose values are dependent on rout ...

Can type safety be maintained while utilizing generics in code?

Suppose I have multiple classes with a similar method for saving models. For example, many services that include a saveModel method: public async saveModel(newModel: IModel): Promise<IModel> { return await newModel.save(); } I created a generic ...

Fledgling angular freshly unboxed

After downloading and installing Visual Studio Community, I proceeded to create a new project: vs v 16.4.0 I created a new ASP.NET Core Web Application using the following steps: File New Project ASP.NET Core Web Application C ...

Should ts-node be avoided in a production environment due to potential risks?

My current setup involves using ts-node with express in production and so far, it's been functioning smoothly. Am I missing out on any benefits by not compiling and running .js files instead? ...

Determine whether a specific date falls within a specific time range

When working with two dates, firstDate and secondDate, I am trying to determine if a new date falls between them but encountering errors. This is the approach I have taken: export class AppComponent { first = "20171212"; second = "20181212"; first ...

Unable to utilize substring within *ngFor directive in Angular

When I iterate through a list of objects using the variable setting, their names are accessible in this format: setting['_name'] The setting names follow this specific format: <name>(<parameters>) I also need to display data from ...

Define the data type of the array within hooks, then proceed with initialization

After attempting to populate the state using data fetched by RNFS.readDir, I encountered an issue where the state was being reinitialized. interface fileUnit { type: string, index: number, title: string, path: string, date: string, size: numbe ...

Utilizing React Router with the power of useCallback

My route configuration is set up as follows: const defineRoutes = (): React.ReactElement => ( <Switch> <Redirect exact from="/" to="/estimates" /> <Route exact path="/estimates" component={CostingPa ...

What is the process for appending an attribute to a DOM element?

Is there a way to conditionally add the multiple attribute to this element? <mat-select [formControlName]="field.name" multiple> I attempted to do so with the following: <mat-select [formControlName]="field.name" [attr.multiple]="field?.mu ...

How to Navigate Between Pages and Push to Tab Pages with Ionic 3 and Angular 4

Currently, I am encountering an issue with transitioning from a Login screen designed as a normal page to a Tab-based Home screen in my application. Despite verifying valid credentials, I have been unable to successfully navigate to the desired Tab-based ...

Tips for securely passing props based on conditions to a functional component in React

I came across this situation: const enum Tag { Friday: 'Friday', Planning: 'Planning' } type Props = { tag: Tag, // tour: (location: string) => void, // time: (date: Date) => void, } const Child: React.FC<Props> = ...

Transfer the view encapsulation id selector to a CSS class within an @Input directive passed down from the parent component

Alright, we all know that using ng-deep is not ideal and that ViewEncapsulation.None can lead to messy code. So here's the dilemma I'm facing. Let's say I have a component with the following; @Input() cssClasses: string; Now, when I use t ...

Issue with Angular polyfill in IE11: The core-js version 3.6.5 method es.string.split.js is having trouble parsing the regex /^|s+/ when used with

Angular 10, d3 5.16.0, and core-js 3.6.5 In the midst of it all, d3-drag triggers d3-dispatch, which in turn invokes a function called .parseTypenames. function parseTypenames(typenames, types) { return typenames.trim().split(/^|\s+/).map(functio ...

Different ways to fulfill the extends type interface requirement in TypeScript

Hey there, I'm looking to create reusable hooks for API requests. Here's the code I have so far: interface DataResponse<Data> { data: Data[]; } export const useRequestInfiniteHooks = <T extends DataResponse<T>>() => { co ...

Moving the sidebar from the app component to a separate component in Angular results in a situation where the sidebar does not maintain full height when the page is scrolled down

Within my Angular application, I have implemented a sidebar as a separate component. Previously, the content of the sidebar was housed within the main app component's HTML page, and it functioned properly by taking up the full height of the page when ...

Switch between every other pair of table rows, then repeat with the following two pairs

I am attempting to create a table with alternating row colors of green and yellow in sets of two. I have been using :nth-child but it is not working correctly. My table is automated using Angular 6 and styled with Angular Material 6. If you would like to ...

Retrieve the file from the REST API without using the window.open method

I'm looking for a method to download files from an API without using window.open(). I want the download process to start immediately upon calling the API. Currently, I am downloading an .xls file generated by a REST API using window.open() API Endpo ...

Incorporate a background image into mat-dialog

I've been struggling to set a background image on my mat-dialog, but for some reason it's not showing up at all. I attempted using a panelClass as well, but still no luck. .custom-panel .mat-dialog-container { background-image: url("../. ...