Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a data-test-id for each record of a list

I am writing an automated test in Cypress to test updating a record in a list of records. I want to test the last record created in the list.

I have tried adding a data-test-id (attr.data-test-id="project-{{id}}") to the HTML and referenced it in my Cypress test.

HTML:

      <mat-list-item
        *ngFor="let project of projects; let id=index"
        (click)="selected.emit(project)"
        attr.data-test-id="project-{{id}}">
        <h3 mat-line>
          {{project.title}}
        </h3>
        <p mat-line>
          {{project.details}}
        </p>

Cypress test:

  describe('#update', () => {
    it('updates a record', (id) => {
      cy.get('[attr.data-test-id="project-${id}"]').click()

    });

I want to pass the index number (id) in the Cypress test, however, I am receiving a "Syntax error, unrecognized expression" message in Cypress. What am I doing wrong? Thanks in advance!

like image 595
DraeDaQA Avatar asked Oct 11 '25 21:10

DraeDaQA


1 Answers

Not familiar with Angular, but from it seems the attr.data- is angular-specific template syntax. The actual HTML it'll produce is going to be standard data- attribute.

Thus, you need to query using:

cy.get(`[data-test-id="project-${id}"]`).click()

Also make sure you use template literals (using backticks: `string`), otherwise your variable id won't get interpolated.

like image 112
dwelle Avatar answered Oct 14 '25 10:10

dwelle