1

I have a field name where the value 1 is not allowed. Per JavaScript I insert the text 'This value is not valid' in form-element when the cursor left the name-field. I would like to test this. I have tried this code:

cy.get('#name').clear().type('1')
cy.get('#street').trigger('click')
cy.get('#street').focus().then(() => {
  cy.get('#form').should('contain.text', 'This value is not valid')
})

Sometimes the test works, sometimes not. In the application itself, the validation works without any problems.

What do I need to do to make sure the code tests valid?

agi
  • 23
  • 2

1 Answers1

2

It looks like you need to use the .blur() command, from the way you describe the user process.

You would think that .focus() to another element would also do it, but maybe the validation is tied into the specific blur event type.

This is how it would look

cy.get('#name').clear().type('1').blur()
cy.get('#form').should('contain.text', 'This value is not valid')

Note there's no need for a .then() wrapper as the commands will process sequentially.

Also try a simple {enter}

cy.get('#name').clear().type('1{enter}')
cy.get('#form').should('contain.text', 'This value is not valid')

Ideally, you want to investigate the source code of the app to see what event or events are involved in the validation process.

It may even be a custom event, for example a validate event that requires the Cypress test to trigger that event.

cy.get('#name').clear().type('1').trigger('validate')
cy.get('#form').should('contain.text', 'This value is not valid')
Joe Krees
  • 36
  • 3