Cypress: is there a way to assert if the value of an input is not empty or at least with some number of chars

12.8k views Asked by At

I have an input that renders some value. I need to check if the value exists, in other words, at least there should be one characters/ letters in the input field.

I have a test like this in Cypress

cy.get('input').should('be.visible').and(($input) => {
  expect($input).to.have.value('')
})

which doesn't work since this test checks if the value is exactly ''. what I want is that the value should be at least of length 1/ non-empty. Is there a way to do it?

3

There are 3 answers

0
Alapan Das On

You can do this by matching the value against a regex. You can get more info from the cypress docs.

cy.get('input').should('be.visible').and(($input) => {
  const val = $input.val()
  expect(val).to.match(/foo/)
})
0
Anastasiia Solop On

One of the possible solutions would be to check the value's length

cy.get('input').should('be.visible').and(($input) => {
  const val = $input.val()
  expect(val.length).toBeGreaterThan(0)
})

0
majkl zumberi On

if you want to type into the input field

cy.get('input').type("here some value")
.should("have.value","here some value")//checks exactly for that string

or if you want to assert that input not be empty

cy.get('input').should('not.be.empty')

i reccommend to check the doc https://docs.cypress.io/api/commands/should.html#Usage