DEV Community

Cover image for How to type and press ENTER with Cypress

How to type and press ENTER with Cypress

walmyrlimaesilv profile image Walmyr Filho Updated on ・2 min read

Today, in “Pinches of Cypress”, learn how to test a search functionality like a real user

When writing end-to-end tests, the tests must simulate using the application as closest to a real user.

Take the DuckDuckGo search site as an example.

When a user searches, they typically type what they are looking for and then press ENTER.

Note: Nothing prevents you from typing in the search field and pressing the magnifying glass button, but normally, users use the ENTER key.

However, both scenarios must be covered by tests.

Let's see how to test such scenarios with Cypress.

// search.spec.js

describe('DuckDuckGo', () => {
  beforeEach(() => {

  it('searches by typing and pressing ENTER', () => {

      .should('contain', '')

  it('searches by typing and clicking the magnifying glass button', () => {

      .should('contain', '')
Enter fullscreen mode Exit fullscreen mode

As you can see in the first test (searches by typing and pressing ENTER), when I call the type() method, in addition to passing the term I want to search for (, I pass the text enter wrapped in curly braces ({enter}). This way, Cypress will type the text and simulate the ENTER key is pressed.


There is nothing new in the other test (searches by typing and clicking the magnifying glass button). First, I type in the field, and then I click the magnifying glass button.


The takeaway here's, test the application as your real users use it and cover as many scenarios as possible. That way, you will be safe to modify the application and know if everything continues to work as expected or if you have broken something and need to fix it before moving on.

To learn more about the cy.type() functionality, I recommend reading the official documentation.

Did you like it?

Leave a comment.

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. Happy testing! 🎉

Discussion (0)

Editor guide