I have a span element which value is 2. I would like to check if the value is greater than 0, but after checked online and implemented every method, it did not work...
Here is the console when I log the $span
I understand that Cypress works asynchronously, so I use .then()
to get the text of element. How can I get the value of 2 and do the follow if-else?
HTML
<div>
<span class="badge ml-1 badge-primary">2</span>
</div>
cy.get(".badge.ml-1.badge-primary").then(($span)=> {
if($span.text().includes(0)) {
doFunction1()
} else {
cy.get(xxxxx)
}
)}
CodePudding user response:
Do it by chaining conversions methods to go from from element
-> text
-> number
cy.get(".badge.ml-1.badge-primary")
.invoke('text') // to text
.then(text => text) // to number
.then(value => {
if(value > 0) {
doFunction1()
} else {
cy.get(xxxxx)
}
})
Waiting for value 2
cy.get(".badge.ml-1.badge-primary")
.invoke('text') // to text
.then(text => text) // to number
.should('eq', 2) // wait for value 2
.then(() => {
doFunction1() // now doFunction
})
CodePudding user response:
What you asked for is to check if content of a span is GRATER THAN 0. So it will require some additional apprach than using includes
. For example you may read a value as a variable and check if it is grater than 0:
cy.get(".badge.ml-1.badge-primary").then(($span)=> {
const value = $span.text(); // now you know what the value is
if(value > 0) { // actual check if > 0. Beware, implicit coersion here! read more below.
doFunction1()
} else {
cy.get(xxxxx)
}
)}
The value
variable, however, is a string. My code works since JS would convert string to number automatically. Depending on your use-case, you might want to make sure it is a valid number and not some other string, which can't be converted to a number (like "2s").
For example, if the value is "2s", than the value > 0
check would be falsy, which might result in a bug in your code.
cy.get(".badge.ml-1.badge-primary").then(($span)=> {
const value = Number.parseInt($span.text()); // now you know what the value is
if(!Number.isNaN(value) && value > 0) { // value is now of type number, but it may be NaN! (yes, NaN is also a number)
doFunction1()
} else {
cy.get(xxxxx)
}
)}
CodePudding user response:
First make sure that the selector that you are using is unique, so that is shouldn't fetch an unintended value. Secondly you can wait with a custom timeout in case your webpage takes some time to populate the value and then apply your if-esle condition. Now instead of 4 seconds(cypress default timeout), the should command will re-try for 7 seconds to check that the element has the inner text value of 2.
cy.get(".badge.ml-1.badge-primary", { timeout: 7000 }).should("have.text", "2")
cy.get(".badge.ml-1.badge-primary")
.invoke(text)
.then((num) => {
if ( num > 0) {
doFunction1()
} else {
cy.get(xxxxx)
}
})