skip to Main Content

I am migrating cypress tests in playwright and I need to find a solution to the following problem. I have a page with dynamic content. I need to get the label values of particular set of the present elements so I can verify them against another page. For example if we get https://playwright.dev/ some of the sections like ‘Any browser’ or ‘No trade-offs’ may or may not be loaded. the locators for the different section stay persistent it’s just they are not necessary loaded on the page(depends on previous actions that are out of my control).
In cypress that was easy enough by creating a const, wrapping it and populate the values in a promise, but I can’t figure out how to do it in playwright.
This is a code sample for the implementation in cypress

 const pageData = {
    values: [],
};

cy.wrap(pageData).as('pageData');
cy.get('@pageData').then((pageData: any) => {

    cy.get('.page')
        .then(($page) => {
            storeValues();
           
            function storeValues() {
                if ($page.find('.widgetWrapper').length) {
                    cy.get('.widgetWrapper').each(($widget, index) => {
                        pageData.values[index] = {
                            name: $widget.find('.name').text()
                        };
                    });
                }
            }
        })
})

2

Answers


  1. You can use evaluateAll

    const result = await page.locator('.widgetWrapper').evaluateAll(
        list => {
          return list.map(element => { name: element.querySelector('.name').innerText})
        });
    
    Login or Signup to reply.
  2. Using allInnerTexts:

    NOTE :This is for simple cases where all nodes have sub nodes having name class.

    Example:

    const texts = await page.locator('.widgetWrapper .name').allInnerTexts();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search