Cypress:如何识别元素是否仅包含数字

use*_*774 2 cypress

请问如何在 cypress 中识别元素是否仅包含数字?我有一个包含一些动态数据的 div,如果数据包含除数字之外的任何内容,我希望看到测试失败。谢谢你的任何想法。

小智 7

使用Number.isNaN(+value)比使用正则表达式更容易,

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
  })
Run Code Online (Sandbox Code Playgroud)

或对于严格整数

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
  })
Run Code Online (Sandbox Code Playgroud)