DEV Community

Cover image for How to fill out and submit forms with Cypress
Walmyr
Walmyr

Posted on • Updated on

How to fill out and submit forms with Cypress

Welcome to the “Pinches of Cypress” series! 🧂

In this series of content in text format with code snippets, you will learn several tricks of the automated testing framework Cypress.io, to make your life easier when writing test scripts.

I will start with something simple, and we will evolve throughout the series, okay?

Let's say you are testing an application that sells event tickets.

In this example application, for a user to buy a ticket, he must fill in some mandatory data, and after submitting the form, he will receive a success message.

Let's say that the mandatory fields are as follows:

  • Full name
  • Email
  • Checkbox that you agree to the terms of service

Let's also imagine that the elements above have unique IDs.

The test would look something like this:

describe('Online tickets selling app', () => {
  beforeEach(() => {
    cy.visit('https://example.com/tickets')
  })

  it('successfully orders a ticket', () => {
    cy.get('#fullName')
      .should('be.visible')
      .type('John Doe')
    cy.get('#email')
      .should('be.visible')
      .type('john-doe@example.com')
    cy.get('#iAgree')
      .should('be.visible')
      .check()
    cy.get('button[type="submit"]')
      .should('be.visible')
      .click()

    cy.contains('You will receive an email to finish the purchase.')
      .should('be.visible')
  })
})
Enter fullscreen mode Exit fullscreen mode

Note that before typing (type), checking (check), or clicking on elements (click), I am ensuring that they are visible (.should('be.visible')). This makes the test more robust.

Finally, I verify that the text "You will receive an email to finalize your purchase" is contained in some element and is visible.

That's it!

I hope you enjoyed it, and stay tuned for the next content in the series. 👋


This post was originally published in Portuguese on the Talking About Testing blog.


Would you like to learn about test automation with Cypress? Get to know my online courses on Udemy.

Top comments (2)

Collapse
 
marcandre profile image
Marc-André Lafortune • Edited

All the .should('be.visible') are redundant as that is already checked by cypress, you should remove them. See docs.cypress.io/guides/core-concep... and docs.cypress.io/guides/core-concep... for details.

Also, finding inputs by ID is not recommended, best use labels. See docs.cypress.io/guides/references/...

Collapse
 
walmyrlimaesilv profile image
Walmyr

This is an extra caution I like to take, which the Cypress team actually recommends.
Watch this chat I had with Cecelia Martinez, Technical Account Manager at Cypress youtu.be/hXfTsdEXn0c