0

Here is the code for the online tutorial to get title of elements:

test.js

it('',function(){
        cy.visit("https://www.simplyrecipes.com/")
        new SRHomePage().getHeroComponentTitle2().then(title => {
           cy.log(title);
        });
    });

SRHomePage.js

export class SRHomePage{
    getHeroComponentTitle2(){
        let title = '';
         cy.get('.showcase__hero .card__title').then($title => {
            title  = $title.text().trim()
        });

        return new Cypress.Promise(resolve => {
            cy.wrap('').then(() => resolve(title))})
    }
}

IN SRHomePage.js, when I use

return new Cypress.Promise(resolve => {
                cy.wrap('').then(() => resolve(title))})
        } 

=> get title

Order is:

1 visithttps://www.simplyrecipes.com/
2 get.showcase__hero .card__title
3 wrap
4 log Gruyère Mushroom Pizza With Balsamic Glaze

If I use

return new Cypress.Promise(resolve => resolve(title))

=> Do not get title

Order is

1 visithttps://www.simplyrecipes.com/
2 log
3 get.showcase__hero .card__title

I really confused the way work for Promise, cy.wrap('') and asynchronous handling in Cypress in this sittuation

Please explain to me, I really know to understand, thank a lot

  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Jan 31 '23 at 10:18
  • The problem is not in the line where you `return new Cypress.Promise` but rather when you try to assign the `title` variable from within the first `.then()` callback. Don't do that. Just return the promise created by `.then()`: `return cy.get('.showcase__hero .card__title').then($title => { return $title.text().trim() });`! – Bergi Jan 31 '23 at 10:20
  • The difference between your two `return new Cypress.Promise()` lines in the one with `cy.wrap()` does not take the value from closure `title` ***until the Cypress queue has run***. Many people (with no understanding of Cypress) assume that the commands are returning promises, when in fact they are running a queue of commands, and the queue is started ***after*** the test code has run through. – Florence.P Feb 01 '23 at 09:02

0 Answers0