Reputation: 4334
I am new to cypress and I just need a little bit of syntax help. My intellisense is not working so I am not sure if this is the correct command. Basically I want to grab the text of an element and store it as a variable. Later on when I perform an assertion against a new element, I want to assert the new element contains the same text from the previous element.
Is this the correct way to store the text of an element? I don't really understand .wrap even after reading it. Belwo I am trying to get the first element (elementExample() is a method performs a cy.get of a element value).
elementExample().index(1).wrap().as('element1');
If somebody can show me an example to store the element and to assert against it, be much appreciated.
Thank you
Upvotes: 0
Views: 892
Reputation: 18586
Assuming that you want to save the innerText, you can do something like this:
cy.get("selector").invoke("text").as("element1")
cy.get("@element1").then((element1) => {
cy.get("selectorelement2")
.invoke("text")
.then((element2) => {
expect(element1).to.equal(element2)
})
})
You can also separately save the inner text and then later assert as well. Something like this:
cy.get("selector").eq(1).invoke("text").as("element1")
//Do something
cy.get("selector").invoke("text").as("element2")
//Do something
cy.get("@element1").then((element1) => {
cy.get("@element2").then((element2) => {
expect(element1).to.equal(element2)
})
})
Assuming elementExample()
translates into cy.get("selector")
then the above code should look like:
elementExample().eq(1).invoke("text").as("element1")
//Do something
elementExample().invoke("text").as("element2")
//Do something
cy.get("@element1").then((element1) => {
cy.get("@element2").then((element2) => {
expect(element1).to.equal(element2)
})
})
.eq()
will get the DOM element at a specific index in an array of elements. .eq(1)
will get the second element. For accessing the first element we have to use eq(0)
.
Upvotes: 3