转到下一页,直到找到元素

问题描述 投票:1回答:1

我正在使用赛普拉斯进行自动化测试。我正在尝试在页面上找到产品,然后单击它。如果产品未在页面上显示,请转到下一个,直到找到为止。我已经尝试了很多事情:while循环,每个循环,简单的cy.get,但它们都不起作用。谁能帮我解决这个问题?

cypress
1个回答
0
投票

您将需要一个递归命令,具体取决于具体情况。没有一种万能的解决方案,但通常看起来像这样:

function findElem ( targetSelector ) {
    // first, we need to query a container (could be table, or a generic item
    //  container). The important thing is, this container must exist on every
    //  page you'll traverse.
    cy.get('.someContainer').then( $container => {
        // synchronously find the target element, however you want. In this
        //  example I use an attribute selector, but you can do whatever you
        //  want.
        if ( $container.find(targetSelector).length ) {
            return true;
        } else {
            return false;
        }
    }).then( found => {
        if ( found ) {

            return cy.log(`found elem "${targetSelector}"`);
        } else {

            // synchronously check if there's a next page/table
            if ( Cypress.$('.nextPageButton').length ) {

                // when know that there is a next page, click it using cypress
                cy.get('.nextPageButton').click();

                // here, assert that next page/table is loaded, possibly by 
                //  asserting that current page/table is removed from DOM

                // then, recurse
                return findElem(targetSelector);
            } else {

                throw new Error(`Couldn't find elem "${targetSelector}" on any page`);
            }
        }
    });
}

it('test', () => {

    findElem(`[data-id="42"]`);
});

解决方案的关键是使用命令组合来查询容器,并进行同步检查(使用jQuery或其他方法)以查找实际元素。在Conditional Testing了解更多信息。

对于具体的实现,您可以参考我提出的类似问题的older answer

© www.soinside.com 2019 - 2024. All rights reserved.