skip to Main Content

I have this code inside my react component:

return (
    <div className="col">
      <div className="card border-secondary mb-3 text-center">
        <div className="card-header"> 
          <h5 data-cy='topicName' className="col-md"> {topicName} </h5> 
          <span> Rol: {capitalize(author)} </span>
        </div>
        
        <div className="card-body text-secondary">
          <p className="card-text">Última actualización: 16/06/2022</p>
        <div className="">                
        </div>
        </div>
      
        <div className="card-footer bg-transparent">
          <Link to='/responses' >
            <button data-cy='accederResponses' className="btn btn-outline-info " onClick={()=> onSetTopic(topicName, workspace_id, author, topicId)}>Acceder</button>
          </Link>
        </div>
      </div>
    </div>              
  );  

i want to load the page in cypress, and click() in the ‘Acceder’ button, but just in the card with the name ‘CA2’.

enter image description here

but i don’t know how.
now i have this in my test:

describe("LOAD OK", function() {
    it("should load without crashing", function() {
      cy.visit("http://localhost:3000");
      cy.contains('[data-cy="topicName"]', 'CA2');
      cy.get('[data-cy="accederResponses"]').click(); //the button in the card 'CA2'
    }); 
   
}); 

2

Answers


  1. Try this :
    describe("LOAD OK", function() {
      it("should load without crashing", function() {
        cy.visit("http://localhost:3000");
        cy.contains('[data-cy="topicName"]', 'CA2')
          .closest('.card-footer')
          .find('[data-cy="accederResponses"]')
          .click();
      });
    });
    
    Login or Signup to reply.
  2. Your HTML sample is malformed, I would assume the .card-body is (or should be) like the following, as it’s semantically correct.

    <div className="card-body text-secondary">
      <p className="card-text">Última actualización: 16/06/2022</p>
    </div>
    

    In this case the test is easiest like this:

    cy.contains('[data-cy="topicName"]', 'CA2')
      .closest('.card')
      .find('[data-cy="accederResponses"]')
      .click()
    

    .closest(selector) is an ancester search, that is it goes up the DOM tree looking for the nearest selector.

    .find(selector) is a descendent search, it goes down the DOM tree looking for selector.

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