soccerway
soccerway

Reputation: 11931

How to get the value from an input field into a const and log it

How to get the text input field value to a 'const' variable in Cypress, so that I can log that variable using cy.log(). The below code doesn't log anything, can someone familiar with Cypress.io please advise

cy.get('input[name="email"]').then(($text)=>{
        const txt = $text.text()
        cy.log(txt)

    })

Upvotes: 85

Views: 134804

Answers (5)

Gerard_dev
Gerard_dev

Reputation: 832

Cypress official solution How do I get an input’s value? suggests something like this code below:

cy.get('input[name="email"]').should('have.value', val)

Upvotes: 60

Brendan
Brendan

Reputation: 4649

From https://github.com/cypress-io/cypress/issues/630

You should be able to do:

cy
  .get('input[name="email"]')
  .invoke('val') 
  .then(text => {
    const someText = text;
    cy.log(someText);
  });

This is working for me in a test on the following element:

<span class="abProgress" style="width: 0%;">100%</span>

Upvotes: 25

soccerway
soccerway

Reputation: 11931

Using invoke('val') instead of invoke('text') worked for my case.

Reminder of the html tag

<input type="text" class="form-control" name="email">

Cypress code

cy.get('input[name="email"]')
  .invoke('val')
  .then(sometext => cy.log(sometext));

Upvotes: 124

Muhammed Moussa
Muhammed Moussa

Reputation: 5195

If you'd like to massage or work with the text prior to an assertion:

cy.get('input').should(($input) => {
  const val = $input.val()
})

using-cypress-faq

Upvotes: 3

Yuqiu G.
Yuqiu G.

Reputation: 345

.contains('your-value') worked for me

Upvotes: -2

Related Questions