skip to Main Content

I am trying to loop through a list of span tags and then assert that all three timestamps displayed are correct on the video. When I ran the test in Cypress I got the following error:

expected [] to include 0:20

it broke after trying to make the first assertion.

I may have overcomplicated writing the test, but I wanted to see if anyone could help by looking at my code and seeing what was wrong. My approach in writing the test was to loop through the list of elements, store each value in an empty array, and then assert them.

describe("Asserting timestamps", () => {
  beforeEach(() => {
    myLoginData
  }
  it("Asserting the right timestamps are displaying in Video")   
  displayedTimeStamp = []; cy.get(".timestamp").each((element) => {
    expect(element).to.exist;
    cy.wrap(element);
      .invoke("text")
      .then((element) => {
        displayedTimeStamp.push(element[0].innerText);
      });

    expect(displayedTimeStamp).includes("0:20") || 
    expect(displayedTimeStamp).includes("0:25") ||
    expect(displayedTimeStamp).includes("0:45")
  });
});
<div class="video-timestamp-editor"
  <div class="video-notes-list"
    <div class=video-note-data">
      <span class="timestamp">0:20</span>
      <span class="video-note-author">Alexander the Great</span>
      <span class="note-text">" This is a note "</span>
    </div>
    <div class=video-note-data">
      <span class="timestamp">0:25</span>
      <span class="video-note-author">Alexander the Great</span>
      <span class="note-text">" This is another note "</span>
    </div>
    <div class=video-note-data">
      <span class="timestamp">0:45</span>
      <span class="video-note-author">Alexander the Great</span>
      <span class="note-text">" This is a third note "</span>
    </div>
  </div>
</div>

2

Answers


  1. You always need to account for the asynchronous nature of Cypress. Your array is empty when the first assertion is evaluated, because the previous command hasn’t been resolved yet.

    You’re right, the approach seem a little overcomplicated. You can check the span text in the same chain of commands with:

              cy.get(".timestamp").each((element) => {
                  expect(element).to.exist;
                  cy.wrap(element)
                      .invoke("text")
                      .should('match', /0:20|0:25|0:45/)
              })
    
    Login or Signup to reply.
  2. If your expecteds will always be 0:20, 0:25, or 0:45, you can consider making them an array of expected values, and use the index of the yielded element to retrieve that expected value.

    const expected = ['0:20', '0:25', '0:45'];
    cy.get(".timestamp").each((element, index) => {
      cy.wrap(element) // implicitly includes expect(element).to.exist
        .should('have.text', expected[index]);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search