Cypress: Prevent a form from submitting

Created on 18 Jan 2018  路  3Comments  路  Source: cypress-io/cypress

Probably a simple question. We have a form somewhere on a page and when the user submits the form the browser will go to a different URL of a website that is not maintained by us. Is there a way to stop this behaviour?

The desired behaviour would be: Cypress sees that the form is submitted. preventDefault and returns that there was a form submit.

question

Most helpful comment

You can attach event listener to the form and stop the event, no? For example in https://github.com/bahmutov/cypress-form-data-with-file-upload/blob/d1b741253a5df1dcf16636e88a045c98330126f7/index.js#L18

cy.get('form').then(form$ => {
  form$.on('submit', e => {
    e.preventDefault()
 })
})

All 3 comments

You can attach event listener to the form and stop the event, no? For example in https://github.com/bahmutov/cypress-form-data-with-file-upload/blob/d1b741253a5df1dcf16636e88a045c98330126f7/index.js#L18

cy.get('form').then(form$ => {
  form$.on('submit', e => {
    e.preventDefault()
 })
})

Thanks for the answer! that works :).

Hey, Can I see the code? I need the same but for pressing {enter} and I am sure I am doing something wrong because this doesn't work.

Was this page helpful?
0 / 5 - 0 ratings