Search code examples
angularangular-materialjestjsangular-testing-library

Unit test case for mat-menu with jest and @testing-library/angular


I have a Component that uses mat-menu from Angular Material UI. When I call fireEvent.click(), I get an error: TestingLibraryElementError: Unable to find role="menu" in console.

This is my test case:

test('it should open pages menu on button click', async () => {
  
  let component = await render(PaginationComponent, {
    imports:[MaterialModule]
  });
  let buttonCLick = fireEvent.click(screen.getByTestId('openChangePageSizeMenu'));
  expect(buttonCLick).toBeTruthy();

  await screen.findByRole('menu');

});

I am not able to point out where I am going wrong. I also read MatMenuHarness documentation from here.

I am using @testing-library/angular and jest.


Solution

  • After doing some digging, the solution that I found is to add hidden: true. After adding this, the test case looks like this:

    test('it should open pages menu on button click', async () => {
      
      let component = await render(PaginationComponent, {
        imports:[MaterialModule]
      });
      let buttonCLick = fireEvent.click(screen.getByTestId('openChangePageSizeMenu'));
      expect(buttonCLick).toBeTruthy();
    
      await screen.findByRole('menu', {hidden:true});
    
    });
    

    NOTE: this works for mat-dialog as well.