skip to Main Content

I would like to click on an element and check if the selected attribute is true

Here is my code

function clickOnInterface(pos, interfaceName) {
    cy.get('[data-test="interface-list"]').contains(interfaceName).click();

    cy.get(`[data-test="interface-list"] ix-event-list-item:nth-child(${pos})`)
        .should("have.attr", "selected", "true");
    }

Cypress gives me this error:

Timed out retrying after 20000ms: expected
‘<ix-event-list-item.hydrated>’ to have attribute ‘selected’ with the
value ‘true’, but the value was ‘selected’

I don’t understand why it has problem here. Since my attribute is selected="true"

2

Answers


  1. You can pass 3 arguments to the should function. Can you try this snippet below.

    cy.get('[data-test="interface-list"]') {
      cy.get('a').should('have.attr', 'selected', 'true');
    }
    

    Source: https://docs.cypress.io/api/commands/should

    Login or Signup to reply.
  2. When you use cy.get(selector).contains(some-text) the element returned is the element containing the text, within the element represented by selector.

    So in your case you end up with div.event-header, but what you really need is ix-event-list-item, since that is where the selected attribute is.

    To go to the correct element,

    • use cy.contains(selector, some-text) format to target the exact element

    • use .should('have.attr', 'selected', 'true') to test the attribute and it’s value

    cy.get('[data-test="interface-list"] ix-event-list-item .event-header')
      .each(($item) => {
        clickOnInterface($item.text());
      })
    
    function clickOnInterface(interfaceName) {
      cy.get('[data-test="interface-list"]').contains(interfaceName).click();
    
      cy.contains('[data-test="interface-list"] ix-event-list-item', interfaceName)
        .should('have.attr', 'selected', 'true');
    }
    

    Note cy.get('[data-test="interface-list"]').contains(interfaceName).click() should be ok if the event bubbles, i.e moves up and down the HTML hierarchy.

    If not, the same approach should be used on that line.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search