Search code examples
angularcypresse2e

Cypress && Angular - get selector from href inside Ngfor


I have a side navigation bar and I'm trying to make a test to click on a link and redirect to the correspondent page.

The selector is inside element that is inside a ngFor loop.

     <ng-container *ngFor="let item of listItems">
        <li>
            <a [data-test]="item.routerLink"></a>
        </li>
    </ng-container>

I already try using a[href] but had no success.

    it('should redirect user to welcome', () => {
        cy.getBySelector('a[href*="/welcome"]').click();
    });

Thank you.


Solution

  • I would recommend creating a unique id for each item making use of the index, and then you can select it with Cypress like the following:

    <ng-container *ngFor="let item of listItems; let i = index">
     <li>
       <a [attr.cy-data]="'myLink-' + i" [data-test]="item.routerLink"></a>
     </li>
    </ng-container>
    
    // * specify the index, here I'm using index 2, "select the 3rd link"
    cy.get("[data-cy='myLink-2']").click();