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 >
<a 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:
<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?
CodePudding user response:
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)
})
})