Triggering Events in ag grid for unit test

Viewed 749

i wanted to trigger ag grid events manually but don't know how

So I have a event tied to a column which is type of cell clicked event, and when you click on it, it opens a mat dialog. So the question is how can you trigger that event for unit testing? I tried to get that cell with Dom and click on it, and also use the grid API but it doesn't work.

it('checking mat dialog option', async ()=>{
jest.spyOn(matDialog,'open');

//using grid api which doesn't work
// component.gridOptions.api.dispatchEvent(cellClikcedEvent);

// using dom
const select= fixture.nativeElement.querySelectorAll('.ag-cell');
select[3].dispatchEvent(new Event('click));
// or  select[3].click();

expect(matDialog.open).toBeCalled();
)

there are typos, i'm writing this question at home and don't have my code , but the logic is some thing like above. there is a really bad documentation about it too. like you don't know how you can use it

1 Answers

I like to use triggerEventHandler for this on the DebugElement.

it('checking mat dialog option', () => {
  jest.spyOn(matDialog,'open');
  
  const cell = fixture.debugElement.query(By.css('ag-grid'));
  // the first string argument is the event you would like to trigger, the second argument is the $event that you would like to mock
  cell.triggerEventHandler('cellClickedEvent', {});
  
  expect(matDialog.open).toBeCalled();
});

I am thinking, the DOM is something like this:

// HTML
<ag-grid
  (cellClickedEvent)="doSomething($event)"
></ag-grid>

// TypeScript
doSomething($event) {
  matDialog.open();
}

Learn more about triggerEventHandler here: https://netbasal.com/simulating-events-in-angular-unit-tests-5482618cd6c6.

Related