首页 > 解决方案 > 如何捕获赛普拉斯下拉列表的所有值?

问题描述

我有一个显示状态列表的下拉框。名单中有大约 40 个国家。每次我向下滚动列表时,列表一次只显示 15 到 20 个状态。

我想捕获列表的所有值并将它们保存在字符串数组中。然后检查字母排序。

如何使用赛普拉斯做到这一点?目前,它仅捕获列表中的前 15 个项目。

这是我的代码:

const verifySortOrdering = (key: string) =>
  getSingleSelectList(key).then(dropdown => {

    cy.wrap(dropdown).click();

    if (dropdown.length > 0) {

      const selector = 'nz-option-container nz-option-item';
      let NumOfScroll = 1;
      const unsortedItems: string[] = [];
      const sortedItems: string[] = [];

      cy.get(selector).then((listItem) => {
        
        while (NumOfScroll < 7) {
          sortAndCheck(selector, unsortedItems, sortedItems);

          if (listItem.length < 15) {
            break;
          }
          NumOfScroll++;
        }

      });
    }
  });


const sortAndCheck = (selector: string, unsortedItems: any, sortedItems: any) => {

  cy.get(selector).each((listItem, index) => {
    if (index === 15) {
      cy.wrap(listItem).trigger('mousedown').scrollIntoView().last();
    }
    unsortedItems.push(listItem.text());   
    sortedItems = unsortedItems.sort();
    expect(unsortedItems, 'Items are sorted').to.deep.equal(sortedItems);
  });
};

标签: cypress

解决方案


这是一个基于您提供的工作示例。添加了额外的检查以确保列表具有正确数量的选项。你可能想要也可能不想要。深度复制未排序的列表,因此由于浅拷贝而不会对其进行排序。在构建 unsortedItems 列表后添加了验证,因此我们可以验证一次,而不是对列表中的每个项目进行验证。

var unsortedItems = new Array()
var expectedListCount = 32
cy.get('#myselect>option').should('have.length', expectedListCount)
.each(($el) => {
    unsortedItems.push($el.text());
}).then(() => {
    var sortedItems = [...unsortedItems]; // deep copy
    sortedItems.sort();
    expect(unsortedItems).to.deep.equal(sortedItems)
})

另一个基于您修改后的示例的示例,但如果没有您的 DDL 的工作示例,我无法验证它。这首先建立 unsortedItem 列表,然后进行比较。

const verifySortOrdering = (key: string) =>
  getSingleSelectList(key).then(dropdown => {
    cy.wrap(dropdown).click();
    if (dropdown.length > 0) {
      const selector = 'nz-option-container nz-option-item';
      let NumOfScroll = 1;
      const unsortedItems: string[] = [];
      const sortedItems: string[] = [];
      cy.get(selector).then((listItem) => {
        while (NumOfScroll < 7) {
          unsortedListBuilder (selector, unsortedItems, sortedItems);
          if (listItem.length < 15) {
            break;
          }

          NumOfScroll++;
        }
      });
    
      var sortedItems = [...unsortedItems];
      sortedItems.sort();
      expect(unsortedItems).to.deep.equal(sortedItems);
    }
  });

const unsortedListBuilder = (selector: string, unsortedItems: any, sortedItems: any) => {
  cy.get(selector).each((listItem, index) => {
    if (index === 15) {
      cy.wrap(listItem).trigger('mousedown').scrollIntoView().last();
    }
    unsortedItems.push(listItem.text());   
  });
};

推荐阅读