0
0
CypressHow-ToBeginner ยท 4 min read

How to Submit Form in Cypress: Syntax and Examples

In Cypress, you can submit a form by selecting the form element and using the .submit() command or by clicking the submit button with .click(). Both methods trigger the form submission and allow you to test form behavior easily.
๐Ÿ“

Syntax

To submit a form in Cypress, you typically select the form element using cy.get() and then call .submit() on it. Alternatively, you can click the submit button inside the form using cy.get('button[type="submit"]').click().

  • cy.get(selector): Finds the form or button element.
  • .submit(): Submits the form directly.
  • .click(): Clicks the submit button to trigger submission.
javascript
cy.get('form').submit();

// Or click the submit button
cy.get('button[type="submit"]').click();
๐Ÿ’ป

Example

This example shows how to fill out a form and submit it using .submit(). It verifies that the form submission triggers the expected behavior.

javascript
describe('Form Submission Test', () => {
  it('fills and submits the form', () => {
    cy.visit('https://example.cypress.io/commands/actions');
    cy.get('#email1').type('test@example.com');
    cy.get('form').submit();
    cy.url().should('include', '/commands/actions');
  });
});
Output
Test passes if form submits and URL includes '/commands/actions'.
โš ๏ธ

Common Pitfalls

Common mistakes when submitting forms in Cypress include:

  • Using .submit() on elements other than the <form> tag, which won't work.
  • Not waiting for form fields to be filled before submitting.
  • Clicking a button that is not the submit button, so the form does not submit.

Always ensure you select the correct form or submit button element.

javascript
/* Wrong: submitting a button element */
cy.get('button[type="submit"]').submit(); // This will fail

/* Right: submit the form or click the button */
cy.get('form').submit();
// or
cy.get('button[type="submit"]').click();
๐Ÿ“Š

Quick Reference

ActionCypress CommandDescription
Submit form directlycy.get('form').submit()Submits the form element directly
Click submit buttoncy.get('button[type="submit"]').click()Clicks the submit button to submit form
Type into inputcy.get('input').type('text')Fills input fields before submission
Check URL after submitcy.url().should('include', 'path')Verifies navigation after form submit
โœ…

Key Takeaways

Use cy.get('form').submit() to submit the form element directly.
Alternatively, click the submit button with cy.get('button[type="submit"]').click().
Always select the correct form or button element to avoid errors.
Fill all required fields before submitting the form.
Verify form submission by checking page changes or URL updates.