Search code examples
cypress

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:

Solution

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