-1

I need to access data outside from then.

   function getText() {
    cy.get('#locator')
        .then(function($elem) {
            let aaa = cy.log($elem.text());
            return aaa.toString();
        });
   }

   var returnedValue = getText();
   cy.log(returnedValue);

I get the error: Argument of type 'void' is not assignable to parameter of type 'string', when I try to print the output in the Cypress test runner log. enter image description here

Ivan Markov
  • 129
  • 4
  • 15
  • 2
    Try returning `cy.get`? (I'm aware that `cy` calls are not "true" promises, so my initial thought of "you can't do that" may be wrong.) – evolutionxbox Oct 03 '22 at 12:36
  • This was already asked just yesterday [Return text from function cypress](https://stackoverflow.com/questions/73926331/return-text-from-function-cypress) – user16695029 Oct 03 '22 at 19:30
  • And here [Return a value from a function in cypress](https://stackoverflow.com/questions/70772883/return-a-value-from-a-function-in-cypress) – user16695029 Oct 03 '22 at 19:31
  • And here [How to return result from Cypress function after set](https://stackoverflow.com/questions/72492152/how-to-return-result-from-cypress-function-after-set) – user16695029 Oct 03 '22 at 19:35
  • 2
    Does this answer your question? [How to return result from Cypress function after set](https://stackoverflow.com/questions/72492152/how-to-return-result-from-cypress-function-after-set) – SuchAnIgnorantThingToDo-UKR Oct 03 '22 at 19:44

1 Answers1

1
  1. Your getText() does not return anything, hence the argument of type void... error.
  2. You're trying to convert a cy.log() command into a string, which is not feasible.

Instead, let's yield the result of your getText() command into a .then() that uses cy.log();

const getText = () => {
  return cy // return the entire chain
    .get('#locator')
    .then(($elem) => {
       return $elem.text(); // return the text of the element
    });
}

getText().then((result) => {
  cy.log(result);
});

If you need to do something besides cy.log() that value, just do the same, and use that result variable.

getText().then((result) => {
  // code that uses result
});

I would not advise declaring a variable and setting it equal to getText(), because that is going to assign the variable a value of type Chainable<string>, and not string, which is not what you want or need.

agoff
  • 5,818
  • 1
  • 7
  • 20