rino
rino

Reputation: 333

get text from an element and store in a variable in cypress

I am trying to get text from an element (input tag) and store it in a variable.

The following statement is used to set data in the text field.

cy.get('app-screen').find('input[id="studentName"]').type("Viola");

I tried to get the value with the following statements:

cy.get('app-screen').find('input[id="studentName"]').then(($text1) => {            
      let textValue1 = $text1.text());
      cy.log('Student Name: ' + textValue1 );                       
    });

cy.get('app-screen).find('input[id="studentName"]').invoke('text').then(text2 => {
  let textValue2 = text2;
  cy.log('Student Name: ' + textValue2 );  
});

In both queries the output was empty, logging the following:

Student Name:

Upvotes: 11

Views: 31363

Answers (3)

Brian E Byrne
Brian E Byrne

Reputation: 246

Generally the best, most reliable way to test this is with a .should() assertion.

cy.get('input[id="studentName"]').type('Viola');

cy.get('input[id="studentName"]').should('have.value', 'Viola')

Inside a function, you would return the result in a Promise.

function getValue(selector) {
  return new Promise(resolve => {
    cy.get(selector)
      .then($input => resolve($input.val()))
}

getValue('input[id="studentName"]')
  .then(value => {
    cy.wrap(value).should('eq', 'Viola')
  })

But Cypress provides Custom Commands to make functions more fluid (you don't need a Promise)

Cypress.Commands.add('getValue', (selector) => {
  cy.get(selector)
    .then($input => $input.val())
})

cy.getValue('input[id="studentName"]')
  .should('eq', 'Viola')

Upvotes: 13

jjhelguero
jjhelguero

Reputation: 2571

You'll have to see check how the element stores the text you are viewing in the UI. NOTE: .invoke('text') used the jquery method .text() which grab the textContent of the element. To get the innerText then you'll have to use a callback function.

If you are looking to log out the text value, then you can do one of the following:

cy.get('app-screen')
  .find('input[id="studentName"]')
  .invoke('val')
  .then(cy.log) // this will log out the text

cy.get('app-screen')
  .find('input[id="studentName"]')
  .then($el => { cy.log($el[0].innerText }) // this will log out the innerText

Upvotes: 5

Alapan Das
Alapan Das

Reputation: 18650

Assuming after the type command the typed value gets saved in the value attribute. Also, you can use alias to save the inner Text something like:

cy.get('app-screen').find('input[id="studentName"]').invoke('val').as('name')
cy.get('@name').then((name) => {
  cy.log('Student Name: ' + name) //prints name
})

Upvotes: 7

Related Questions