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

Viewed 5104

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

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

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

Tried with the below statements to get the text:

 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 ways the output was empty as below.

Student Name:

Could anyone please help to sort this issue?

2 Answers

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
})

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

Related