please how to identify in cypress, if element contains only numbers? I have a div which contains some dynamic data and I would like to see to fail the test, if the data will contain anything but numbers. Thanks for any idea.
please how to identify in cypress, if element contains only numbers? I have a div which contains some dynamic data and I would like to see to fail the test, if the data will contain anything but numbers. Thanks for any idea.
You can use match() and then compare it with a regex. The /^[0-9]*$/ regex value will only check for numbers.
cy.get('#greeting')
.invoke('text')
.should('match', /^[0-9]*$/)
Thanks, @Prabhu Mohan for this. If you are checking the numbers that contain decimals, you can use -
cy.get('#greeting')
.invoke('text')
.should('match', /^[0-9]\d*(\.\d+)?$/)
Using Number.isNaN(+value) is easier than using a regex,
cy.get('input')
.type('123')
.invoke('val')
.should(value => {
expect(Number.isNaN(+value), 'input should be a number').to.eq(false) // passes
})
cy.get('input')
.type('123.45')
.invoke('val')
.should(value => {
expect(Number.isNaN(+value), 'input should be a number').to.eq(false) // passes
})
cy.get('input')
.type('abc')
.invoke('val')
.should(value => {
expect(Number.isNaN(+value), 'input should be a number').to.eq(false) // fails
})
or for strictly integer numbers
cy.get('input')
.type('123')
.invoke('val')
.should(value => {
expect(Number.isInteger(+value), 'input should be an integer').to.eq(true) // passes
})
cy.get('input')
.type('123.45')
.invoke('val')
.should(value => {
expect(Number.isInteger(+value), 'input should be an integer').to.eq(true) // fails
})
cy.get('input')
.type('abc')
.invoke('val')
.should(value => {
expect(Number.isInteger(+value), 'input should be an integer').to.eq(true) // fails
})
You can achieve this using regular expression. Refer for an idea https://docs.cypress.io/api/commands/contains#Regular-Expression