I wrote a function that extracts the text of a web element.
getText(selector) {
let textValue;
cy.get(selector).then(($value) => {
textValue = $value.text() // working
return textValue; // not returning anything
})
}
How can I make getText(selector)
return textValue
?
Helper.js class
class Helper {
getText = (selector) => {
return cy.get(selector).invoke('text')
.then(text => {
return text.trim() // added to show a .then() step inside function
})
}
}
StepDefs.js
Given("This is demo test", async function (string, string2) {
const helper = new Helper()
cy.visit("https://google.com");
// get Images link text
let imageText;
imageText = helpers.getText(':nth-child(2) > .gb_q').then(trimmedText => {
expect(trimmedText).to.eql('Images'); // this assertion is passing
return trimmedText
})
// imageText is not storing a string "Images", but an Object
cy.task('log', imageText) // it prints [Object object]
}