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.
CodePudding user response:
- Your
getText()
does not return anything, hence theargument of type void...
error. - 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.