Changing tabs in Angular Material using Cypress

2.6k Views Asked by At

I have an Angular Material tab group on my page. I have to test changing of tabs using Cypress. When the page loads the user is on the Basic Information tab, I want to switch to the Relationships tab. I am not able to change the tabs

Here's the code:

<mat-tab-group animationDuration="0ms">

  <mat-tab label="Basic Information">
  </mat-tab>

  <mat-tab data-cy="relationship-tab" label="Relationship" *ngIf="leiType.value===leiTypes.CORPORATION">
  </mat-tab>

  <mat-tab label="Address">
  </mat-tab>
</mat-tab-group>

I am using the click event on the label to change the tab, but to no avail.

cy.get(`[data-cy='relationship-tab']`).click();
// cy.get(`[data-cy='relationship-tab']`).trigger('click');

I get the following error:

Timed out retrying: Expected to find element: [data-cy='relationship-tab'], but never found it.
3

There are 3 best solutions below

1
On

I accomplished that by

cy.get('.mat-tab-label').contains('Relationship').click()

0
On

Hence the mat-tab is not rendered to the DOM one-in-one, you should consider other options. As of now, the mat-tab is included in the DOM like this:

<div role="tab" ... >

So if you are on a page where you do not have any other div's with role tab, you can select this based on cypress css selector, with the following set-up.

// Select second tab
cy.get('div[role=tab]').eq(1).click();

By the way, relying only this css selector is not in the best practices, but I hope I was able to help you.

6
On

How about waiting the tag to be visible and then clicking on it, this works for me always:

cy.get('[data-cy="relationship-tab"]').should('be.visible');    
cy.get('[data-cy="relationship-tab"]').click();