Given the below form, how do we get any individual input’s value inside a Cypress test?
<form>
<input type="text"
name="code"
data-cy="code">
<input type="tel"
name="phone"
data-cy="phone">
</form>
Using Cypress’s API methods
If you need to hold a reference to the value, you can query it using one of the methods below.
cy.get('[data-cy=code]').should(($input) => {
const value = $input.val();
console.log(value); // do something with the value
})
cy.get('[data-cy=code]').invoke('val').should((value) => {
console.log(value);
})
Querying the DOM
You can also retrieve an input’s value by querying the DOM directly.
cy.document().then((doc) => {
const value = doc.querySelector('[data-cy=code]').value;
console.log(value);
});
Note that to access the test page’s document, we have to use the cy.document()
command to obtain a reference. The document
you access as a global belongs to the Cypress runner, but the test page is inside an iFrame which has a different document reference.