3

I'm trying to check if an has a value of less than x. What's the best way to test that in Cypress?

Example code (that doesn't work):

cy.get('.number-input').type('200').should('have.value.lt', '201')

I know I could do this with a callback, but that seems a bit messy, especially given how neat it is to test if the input is -exactly- something:

cy.get('.number-input').type('200').should('have.value', '200')

1 Answer 1

3

Chai lt is valid (see Chai.js cheatsheet), but it requires numeric values and <input /> value is always a string, so you will need to convert it to a number.

Also, the Cypress .should('have.value.lt', '201') command is a combination of jQuery and chai operators, which from the error message is obviously illegal (the syntax for should params is a bit opaque, you just have to try things out).

So, this works

cy.get('.number-input').type('200')
  .invoke('val')                         // call the val() method to extract the value
  .then(val => +val)                     // convert it to a number
  .then(val => console.log(typeof val))  // just to check the type
  .should('be.lt', 201)                  // also compare it to a number
2
  • Beautiful, thank you! It all makes much more sense now. So the shortest way to do this would be cy.get('.number-input').type('200').invoke('val').then(val => +val).should('be.lt', 201) then? Commented Jun 18, 2020 at 21:24
  • Correct, I just threw in the console.log to show how you can check things within a command chain. Commented Jun 18, 2020 at 21:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.