Home > Software engineering >  How can I find 3rd object in my array in cypress
How can I find 3rd object in my array in cypress

Time:08-16

For my this method

static getTemplateItemName() {
  const x = this.templateItem.find('.template-name').contains('Basic elements').scrollIntoView({ensureScrollable: false});
  cy.get('.template-cover').eq(2).within(() =>
    cy.get('.btn-link-primary').contains('Preview').click({force: true});
};

I want to remove .eq(2) and give something more soft code, which can use other templeate name also. Can you please suggest how we can do it

Here's my HTML:

<div _ngcontent-nbr-c91="" >
  <div _ngcontent-nbr-c91="" >
    <div _ngcontent-nbr-c91="" >
      <p _ngcontent-nbr-c91="" >Basic elements</p> 
    </div>
    <div _ngcontent-nbr-c91="" >
      <button _ngcontent-nbr-c91="" >Preview</button>
      <button _ngcontent-nbr-c91="" > Select </button>
    </div>
    <!---->
  </div>
</div>

Thanks

CodePudding user response:

So instead of eq(2) you can use parent to reach your template cover element and then using within you can click the Preview button. Something like this:

cy.contains('p', 'Basic elements')
  .parent() //template-name
  .parent() //template-description
  .parent() //template-cover
  .within(() => {
    cy.contains('button', 'Preview').click({force: true})
  })

CodePudding user response:

If you Preview and Select buttons are unique only to the div with template-cover you are seeking, then you can easily access.

// make sure we are in correct template
cy.contains('.template-cover', 'Preview')
  .should('be.visible')
  .contains('button', 'Preview')
  .should('be.visible')
  // your element might be covered by another element for you to use force:true
  .click({force:true})
  

If the buttons are not unique to the template then we can go by the template name.

// make sure we are in correct template
cy.contains('.template-cover', 'Basic elements')
  .should('be.visible')
  .contains('button', 'Preview')
  .should('be.visible')
  // your element might be covered by another element for you to use force:true
  .click({force:true})
  
  • Related