https://cypress.io logo
Is there a way to return a synchronous value ?
# i-need-help
b
Hello, I meet a big problem with Cypress sometimes. To avoid duplication code I’ve made a method that should return a value that I get like that :
Copy code
getTextValueFromElement(){
  let text;
  cy.get('elementClass').then($element => {text = $element.text()}
  return text;
}
But I meet this error message sometimes :

https://cdn.discordapp.com/attachments/1096371322042466354/1096371322398965800/IMG_3963.png

Is there a way to force it ? I don’t care about the fact it doesn’t make sense, I just want to use my text attribute everywhere I want 🥲
And I can’t put another .then() because it’s a method used on some other test file. Not directly used in a test.
And the error message doesn’t explain a way to do it.
b
Im very noob at Cypress so I cant promise I can answer followup questions. Perhaps you can try to use cy.wrap around it, then later use the value like this
Copy code
getTextValueFromElement(){
  let text;
  cy.get('elementClass').then($element => {text = $element.text()}
  return cy.wrap(text);
}
Copy code
cy.getTextValueFromElement("element").then(data => {
     // Do whatever you need to do with data
})
b
I did some tricky thing with cy.wrap() that seem to works but, in my mind, it’s not the most understandable thing to do. It should be nice that Cypress allow us to return, by forcing it, a synchronous value
g
Think: can you return both the promise and a value from it? No. You can to write simpler tests: use https://github.com/bahmutov/cypress-map
b
I will take a look at it ! Thanks 🙏🏻