How to Assert Input Value in Cypress: Simple Guide
To assert an input value in Cypress, use
cy.get() to select the input element and then should('have.value', 'expectedValue') to check its value. This verifies that the input contains the exact text you expect.Syntax
Use cy.get(selector) to find the input element by CSS selector. Then use should('have.value', expectedValue) to assert the input's current value matches expectedValue.
This checks the value property of the input element.
javascript
cy.get('input#username').should('have.value', 'myUser')
Example
This example shows how to visit a page, type into an input, and then assert the input value is correct.
javascript
describe('Input value assertion', () => { it('checks input value after typing', () => { cy.visit('https://example.cypress.io/commands/actions') cy.get('.action-email') .type('test@example.com') .should('have.value', 'test@example.com') }) })
Output
Test passes if the input contains 'test@example.com'; fails otherwise.
Common Pitfalls
- Using
should('contain', value)instead ofshould('have.value', value)will not work becausecontainchecks text content, not input value. - Not waiting for the input to be ready before asserting can cause flaky tests.
- Using incorrect selectors can cause the test to fail silently or select wrong elements.
javascript
/* Wrong way: */ cy.get('input#email').should('contain', 'user@example.com') /* Right way: */ cy.get('input#email').should('have.value', 'user@example.com')
Quick Reference
Remember these quick tips when asserting input values in Cypress:
- Use
cy.get(selector)to select inputs. - Use
should('have.value', expectedValue)to check input values. - Ensure the input is visible and ready before asserting.
- Use precise selectors to avoid ambiguity.
Key Takeaways
Use cy.get() with should('have.value', expectedValue) to assert input values.
Avoid using should('contain') for input value checks; it checks text content instead.
Always ensure the input element is ready before asserting its value.
Use clear and specific selectors to target the correct input element.