Alex77
Alex77

Reputation: 25

how to compare numbers in cypress

I'm new to Cypress and I need to compare theese two numbers: 1045,92 and 1045,92

<div class="header-icon__text" data-pl-cart-in- 
total>1&nbsp;045,92&nbsp;р.</div>
<span>1 045,92 р.</span>

I try like this

 cy.xpath("").invoke('text').then((text1) => {
   
 cy.xpath("").invoke('text').then((text2) => {
      
 expect(text1).to.deep.equal(text2); 

But:

AssertionError:

expected '1 045,92 р.' to deeply equal '1 045,92 р.'

And I try like this:

cy.xpath("").invoke('text').then((text1) => {
   
cy.xpath("").invoke('text').then((text2) => {

expect(Math.floor(text1)).to.deep.equal(Math.floor(text2)); 

assert expected NaN to deeply equal NaN

But:

I'm not sure that NaN is 1 045,92

Upvotes: 0

Views: 917

Answers (3)

Alapan Das
Alapan Das

Reputation: 18626

You can do like this:

cy.xpath('selector1')
  .invoke('text')
  .then((text1) => {
    cy.xpath('selector2')
      .invoke('text')
      .then((text2) => {
        expect(text1.replace(/\D/g, '')).to.eq(text2.replace(/\D/g, ''))
      })
  })

.replace(/\D/g, '') will replace all non-Digit characters from the string.

Upvotes: 1

J.Goursaud
J.Goursaud

Reputation: 155

The part &nbsp; stands for non-breaking-space, it is used on a web page to stop a string with a space in the middle from breaking or splitting into two lines.

It can interfere with the comparison, as you found out.

This is how to clear it

cy.xpath("").invoke('text').then((text1) => {
  cy.xpath("").invoke('text').then((text2) => {

    const val1 = text1.replace(/\s/g, ' ')   // clear both "&nbsp;"
    const val2 = text2.replace(/\s/g, ' ')   // making them ordinary space
    expect(val1).to.equal(val2); 
  })
})

Upvotes: 5

zangab
zangab

Reputation: 436

// This should do it. No need for a `deep.equal` here.
expect(text1).to.eq(text2);

I guess u pass these values as a string? But if you compare them string-like or number-like shouldn't matter, values should be identical.

And NaN is due to the , (and the space between 1 and 0) as this should be a ., like 1045.92. NaN means Not a Number meaning your casting (Math.floor()) fails due to prior reasons.

Upvotes: 0

Related Questions