3

So, I have the elements in the following structure:

<div class="MuiBox-root" data-testid="all-events">
  <ul ....>
    <div class="MuiBox-root" data-testid="event">
    <div class="MuiBox-root" data-testid="event">
    <div class="MuiBox-root" data-testid="event">

Now, within each event element is the following structure:

 <div class="MuiBox-root" data-testid="event">
  <li .....>
    <div class="MuiBox-root ....." data-testid="event-status">
      <div> Text Value </div>
    <div class="MuiBox-root ....." data-testid="event-name">
    

So, what I want to test is that if the element event-status is say completed or active, then the element event-name will be present. So the approach that I am using is as follows:

cy.get("[data-testid='events']").its("length").then((numEvents) => {
  for (let i = 0; i < numEvents; i++) {
    cy.get("[data-testid='event-status']").each((status, index) => {
      if (index === i) {
        if (isEventActive(status)) {
          cy.get("[data-testid='event-name']").each((name, index) => {
            if (index === i) {
              cy.get(name).should("have.text", "some value");
            }
          });
        } else {
            cy.get("[data-testid='event-name']").each((name, index) => {
            if (index === i) {
              cy.get(name).should("not.exist");
            }
          });
        }
      }
    });
  }
});

The above code is working to test what I want to test out but it is incredibly messy and any simpler approaches are welcome.

Sayantan Ghosh
  • 368
  • 5
  • 22
  • You can replace that `index === 0` check with something more flexible like `if (event-status === 'condition')` – Joshua Dec 25 '20 at 09:15

1 Answers1

5

Convert the for loop to an .each(). Using .within() on the event will allow internal get commands to be specific to the event, and eliminate the need to check index values.

cy.get("[data-testid='events']").each($event=> { 
  cy.wrap($event).within(() => {
    cy.get("[data-testid='event-status']").each($status => {
      if (isEventActive($status)) {
        cy.get("[data-testid='event-name']").should("have.text", "some value");
      }) else {
        cy.get("[data-testid='event-name']").should("not.exist")
      })
    })
  })
});

Maybe this will also work. Uses closure to get the two inner elements ($status and $name) into a ternary expression, and uses .should("satisfy", callbackFn) to do an either/or check.

cy.get("[data-testid='events']").each($event => { 
  cy.wrap($event).find("[data-testid='event-status']").then($status => {
    cy.wrap($event).find("[data-testid='event-name']")
      .should("satisfy", $name => isEventActive($status)  
        ? $name.text() === "some value"
        : $name.length === 0;
      );
    })
  })
});