Home > database >  How to switch Angular Tab in a Cypress Test
How to switch Angular Tab in a Cypress Test

Time:05-26

I have a Signup/Signin Angular Material Form

  <mat-tab-group >
    <mat-tab label="Sign Up">
      <app-signup></app-signup>
    </mat-tab>
    <mat-tab id="idTabSignIn" label="Signin">
      <app-signin></app-signin>
    </mat-tab>
  </mat-tab-group>

I want to build a cypress test like

  1. Switch Tab to Signin.
  2. Fill Form.
  3. Click Sign in.

two and three is no Problem, but I struggle with 1. How I can switch the tab with Cypress?

My code so far

describe('Signin', () => {
  it('Sign with existing account', function () {
    cy.visit('/')
    cy.get('#idTabSignIn').click()   <---ERROR: idTabSignIn not found
  })
})

CodePudding user response:

What version of Cypress are you using?

Presuming it is the latest version there are two ways to approach this problem both with a common first step.

Common first step:

  1. Change your HTML code to include the data-cy attribute like so:
<mat-tab data-cy="id-tab-sign-in" id="idTabSignIn" label="Signin">
      <app-signin></app-signin>
</mat-tab>

And then approach number one:

  1. Start your cypress runner with watcher. Typically it is ng e2e --watch
  2. enter image description here Click on the New Spec File button.
  3. Name your spec file.
  4. Point and click your test and click save when done.

You can now open this auto-generated test in your IDE and edit as needed.

Approach number two:

  1. Change your code to cy.get('[data-cy="id-tab-sign-in"]').click();

Using the data-cy attribute is one of the "best practices" suggested in Cypress documentation. I personally have found the name attribute to also be useful when attempting to generate e2e tests which must run on different harnesses (Cypress, Selenium, Appium etc).

CodePudding user response:

The Angular Material library does not propagate attributes like id or data-cy through to the running page, so Cypress is unable to use them.

This is what you see in dev-tools

<div >Signin</div>

IMO the best approach is based on the label text which is moved from the attribute in source to element content on the page.

cy.contains('div.mat-tab-label-content', 'Signin').click()

There can be multiple versions of the tab if you have responsive variations (desktop, mobile), so you may need strengthen the selector context, for example

cy.contains('mat-tab-group.signupDiv div.mat-tab-label-content', 'Signin').click()
  • Related