Kavita Rajkumar
Kavita Rajkumar

Reputation: 51

How to get the value for data-id in cypress

I need to get the value for data-id but when I use the below code it does not return any.

cy.get('[data-nemo=token]')
  .invoke('attr', 'data-id').then(dataId => {
    cy.log('dataId : ', dataId);`enter code here`
  });

Thanks,

Upvotes: 4

Views: 13516

Answers (2)

Derek Henderson
Derek Henderson

Reputation: 9706

As per Cypress docs, you can use cy.invoke to call a jQuery method. So, just as in jQuery, you would do

$('[data-nemo=token]').data('id');

in Cypress it's

cy.get('[data-nemo=token]').invoke('data', 'id');

If you then want to use that value, you can either use .then or create an alias with .as and reference the alias later in your tests:

cy.get('[data-nemo=token]')
  .invoke('data', 'id')
  .then(dataId => cy.log('dataId : ', dataId));

or

cy.get('[data-nemo=token]')
  .invoke('data', 'id')
  .as('dataId');

cy.get('@dataId')
  .then(dataId => cy.log('dataId : ', dataId));

Upvotes: 8

soccerway
soccerway

Reputation: 11991

Can you try the below code and see if that is working. Try using data() or attr() option to get id ;

cy.get('[data-nemo=token]').then(($div) => {
        const dataId = Cypress.$($div).attr("data-id");
            // or
        const dataID = Cypress.$($div).data("id");
           // or
        const mydataID = Cypress.$(this).attr("data-id");
        console.log(mydataID);
});

Upvotes: 2

Related Questions