0
0
CypressHow-ToBeginner ยท 3 min read

How to Type Text in Cypress: Syntax and Examples

In Cypress, you type text into input fields using the .type() command chained to a selector that targets the input element. For example, cy.get('input').type('Hello') finds the input and types 'Hello' into it.
๐Ÿ“

Syntax

The basic syntax to type text in Cypress is chaining the .type() command to a selector that finds the input element. The selector is usually done with cy.get(). The .type() command takes a string argument which is the text you want to enter.

  • cy.get('selector'): Finds the input element on the page.
  • .type('text'): Types the given text into the found element.
javascript
cy.get('input').type('Your text here')
๐Ÿ’ป

Example

This example shows how to type the text 'Hello Cypress!' into an input field with the id username. It demonstrates selecting the input and typing text into it.

javascript
describe('Type Text Example', () => {
  it('types text into input field', () => {
    cy.visit('https://example.cypress.io/commands/actions')
    cy.get('#username').type('Hello Cypress!')
    cy.get('#username').should('have.value', 'Hello Cypress!')
  })
})
Output
Test passes if the input #username contains 'Hello Cypress!' after typing.
โš ๏ธ

Common Pitfalls

Common mistakes when typing text in Cypress include:

  • Using a wrong or non-unique selector, so Cypress cannot find the input.
  • Trying to type into elements that are not input or textarea fields.
  • Not waiting for the element to be visible or enabled before typing.
  • Typing special keys incorrectly (like Enter or Backspace) without using curly braces.

Always ensure your selector is correct and the element is ready for input.

javascript
/* Wrong way: typing into a non-input element */
cy.get('div').type('Hello') // This will fail

/* Right way: typing into an input element */
cy.get('input#search').type('Hello')
๐Ÿ“Š

Quick Reference

CommandDescriptionExample
cy.get('selector')Selects an element on the pagecy.get('input#email')
.type('text')Types the given text into the selected element.type('Hello World')
.type('{enter}')Types special keys using curly braces.type('{enter}')
cy.get().should('have.value', 'text')Asserts the input value after typingcy.get('input').should('have.value', 'Hello')
โœ…

Key Takeaways

Use cy.get() to select the input element before typing.
Use .type('text') to enter text into input or textarea fields.
Ensure the element is visible and enabled before typing.
Use curly braces for special keys like Enter or Backspace.
Verify input value with assertions after typing.