我正在使用 Cypress 进行自动化测试。我正在尝试在页面上查找产品并单击它。如果该产品未显示在页面上,请转到下一个产品,直到找到该产品。我已经尝试了很多东西:while 循环、每个循环、简单的 cy.get 但它们都不起作用。谁能帮我解决这个问题吗?
您将需要一个递归命令,其实现取决于您的具体场景。没有一刀切的解决方案,但通常它看起来像这样:
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 或其他方式)来查找实际元素。在条件测试中了解更多信息。
具体实现可以参考我之前类似问题的回答。
| 归档时间: | 
 | 
| 查看次数: | 1831 次 | 
| 最近记录: |