Home > Blockchain >  how to extract numeric value out of text ,along with converting it into number in Cypress
how to extract numeric value out of text ,along with converting it into number in Cypress

Time:06-30

hi folks as i am new into this cypress and UI automation I need your help in resolving current scenario i have a grid like this enter image description here i have created a custom command in support\commands.js below is my code which take OrderID as parameter and read the Freight info from ui but it has lot of nested div tab for padding hence i use parents() tag to reach the specific index row

Cypress.Commands.add('readFreightInfo', (OrderID) => {
  return cy.get('.simple-table__cell:nth-child(1)')
    .contains(OrderID)
    .parents("div[role='row']")
    .find('div')
    .eq(2)
    .invoke('text')
})

but the text it is returning is '\n 65.88' what i needed i needed the number part only i.e. 299.88 in Number type

as it was a generic method for validation i was using earlier

cy.readFreightInfo(10250).should('eq', 65.83)

but now I want to assert it as the returning value of custom command should lies between 60 and 70

what i have tried so far

i have tried using both the workaround mentioned on this answer

solution link i have tried

CodePudding user response:

You can return the value from custom command like this:

Cypress.Commands.add('readFreightInfo', (OrderID) => {
  cy.get('.simple-table__cell:nth-child(1)')
    .contains(OrderID)
    .parents("div[role='row']")
    .find('div')
    .eq(2)
    .invoke('text')
    .then((text) => {
      return cy.wrap( text.replaceAll('\n ', '')) //returns 65.83 as number
    })
})

And then in your test, you can do like this:

cy.readFreightInfo(10250).then((numValue) => {
  cy.wrap(numValue).should('eq', 65.83) //direct assert
  cy.wrap(numValue).should('be.gte', 60).and('be.lte', 70) //greater than equal to 60 and less than equal to 70
})

CodePudding user response:

.trim() removes line terminatiors from both ends of the text.

Also, shortcut for getting the row - use .contains('[role="row"]', OrderId).

Cypress.Commands.add('readFreightInfo', (OrderID) => {

  cy.contains('div[role="row"]', OrderID)
    .find('div')
    .eq(2)
    .invoke('text')
    .then(text => parseInt(text.trim()) )
})

cy.readFreightInfo(10250)
  .should('be.within', 60, 70)

Ref string.trim()

The trim() method removes whitespace from both ends of a string and returns a new string, without modifying the original string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).

  • Related