I have a scenario where after selecting a particular product the amount is reflected in a textfield and when we click on a checkbox the amount doubles automatically. This is my code:
cy.getBySel('textfield').click().then(($title) => {
const op1 = $title.val().replace('$', " ").trim()
cy.log(op1) -- Here i get the amount without the currency ; an amount example can be 25,15
const totalProduct = op1 * 2 ,
cy.log(totalProduct) //when i print here i get NaN
cy.get('#product-checkbox').click()
cy.getBySel('textfield').click().should('have.value', totalProduct)
// Here i need to check the value is equal to op1*2 that is totalProduct
When I am running the test, I am getting:
expected <input> to have value NaN, but the value was 50,30 $
Can someone please advise why I am getting NaN even if I am trimming the currency?
All values taken from the page are text.
To do math on it, convert to a number first.
const op1 = $title.val().replace('$', " ").trim()
const totalProduct = +(op1.replace(',', '.')) * 2
cy.get('#product-checkbox').click()
cy.getBySel('textfield').click()
.should('have.value', totalProduct.toLocaleString('de-DE'))
The final line comparing text values above is using two strings, but it might be more precise to compare numbers instead.
const op1 = $title.val().replace('$', " ").trim()
const totalProduct = +(op1.replace(',', '.')) * 2
cy.get('#product-checkbox').click()
cy.getBySel('textfield').click()
.should($title2 => {
const op2 = $title2.val().replace('$', " ").trim()
expect(op2).to.eq(totalProduct) // compare numbers
})
You can go one more step, make a function of the conversion
const toNumber = ($el) => {
return +($el.val().replace('$', " ").trim().replace(',', '.'))
}
const totalProduct = toNumber($title) * 2
cy.get('#product-checkbox').click()
cy.getBySel('textfield').click()
.should($title2 => {
const op2 = toNumber($title2)
expect(op2).to.eq(totalProduct) // compare numbers
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With