Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to yield span value in Cypress, so it can be compared later

I want to compare two different variables in Cypress, and expect them to be equal using:
expect(var1).equal(var2), however I’m not able to properly gather span value from it, as in example of HTML below.

HTML

    <div class="cat-results">
      <a class="cat-results-url" title>
        <span>Title I want to compare</span>
      </a>
    </div>

I want to get only "Title I want to compare" value, but when I define it in Cypress I get following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<failure message="expected { Object (userInvocationStack, specWindow, ...) } to equal { Object (userInvocationStack, specWindow, ...) }" type="AssertionError"><![CDATA[AssertionError: expected { Object (userInvocationStack, specWindow, ...) } to equal { Object (userInvocationStack, specWindow, ...) }

I know that error is probably caused by me not able to define span text properly, instead Cypress is yielding it in unexpected place, which expectantly causes an error.

What I do is, define:

const var1 = cy.get('.cat-results-url').eq(0), same with var2, then compare.

Are you able to help with direct how to yield this span value properly?

>Solution :

You can do like this. Save the inner text in an alias and then later extract it and compare it with the element 2.

cy.get('a.cat-results-url span').invoke('text').as('titleText')

cy.get('@titleText').then((titleText) => {
  cy.get('selector').should('have.text', titleText)
})

If you don’t want to use alias then you can directly assert as well like this:

cy.get('a.cat-results-url span')
  .invoke('text')
  .then((text1) => {
    cy.get('element2')
      .invoke('text')
      .then((text2) => {
        expect(text1).equal(text2)
      })
  })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading