0
0
Cypresstesting~15 mins

cy.type() for text input in Cypress - Build an Automation Script

Choose your learning style9 modes available
Enter text into a username input field and verify the input value
Preconditions (2)
Step 1: Locate the username input field by its id 'username'
Step 2: Type the text 'testuser' into the username input field
Step 3: Verify that the username input field contains the text 'testuser'
✅ Expected Result: The username input field should display the text 'testuser' after typing
Automation Requirements - Cypress
Assertions Needed:
Verify the input field contains the typed text 'testuser'
Best Practices:
Use cy.get() with a stable selector (id or data-cy attribute)
Use cy.type() to simulate user typing
Use should('have.value', ...) assertion to verify input value
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('Username input field test', () => {
  beforeEach(() => {
    cy.visit('/login');
  });

  it('types text into username input and verifies it', () => {
    cy.get('#username')
      .should('be.visible')
      .and('be.enabled')
      .type('testuser')
      .should('have.value', 'testuser');
  });
});

This test visits the login page before each test to ensure a fresh start.

It locates the username input field by its id #username, which is a stable and clear selector.

We check that the input is visible and enabled before typing to avoid errors.

Using cy.type('testuser') simulates the user typing the text.

Finally, we assert that the input's value matches the typed text using should('have.value', 'testuser').

This approach follows Cypress best practices by avoiding hard waits and using built-in automatic waiting.

Common Mistakes - 3 Pitfalls
Using a fragile selector like XPath or overly complex CSS selectors
{'mistake': 'Using cy.wait() with fixed time before typing', 'why_bad': 'Fixed waits slow down tests and can cause flakiness if the page loads slower or faster.', 'correct_approach': "Rely on Cypress automatic waiting and assertions like should('be.visible') before typing."}
{'mistake': 'Not verifying the input value after typing', 'why_bad': 'Without verification, the test does not confirm if typing actually worked.', 'correct_approach': "Always assert the input's value with should('have.value', expectedText) after typing."}
Bonus Challenge

Now add data-driven testing to type three different usernames and verify each

Show Hint