Owen Versteeg
Owen Versteeg

Reputation: 348

What's the right way to check if an input has a value less than x in Cypress?

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')

Upvotes: 3

Views: 2963

Answers (1)

Richard Matsen
Richard Matsen

Reputation: 23483

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

Upvotes: 3

Related Questions