首页 > 解决方案 > 获取赛普拉斯数组中不包含值的第一个元素

问题描述

我有一个卡片列表,我需要以编程方式选择列表中不包含数组中五个值之一的第一个。我试过这个:

cy.get('.parent-element').not().contains('string1', 'string2', 'etc')

和这个:

cy.get('.parent-element').not('string1', 'string2', 'etc')

嗯。对此有任何想法。的任何子元素.parent-element都是公平游戏,除了这几个例外。

标签: testingautomationautomated-testscypressend-to-end

解决方案


const selector = ".parent-element li";
const array = ["string1", "string2", "string3"];
cy.get(selector)
  .then($els => {
    return $els.filter((i, el) => {
      // Cypress.$ is jQuery
      const textContent = Cypress.$(el).text();
      const result = array.filter(str => textContent.includes(str));
      // if noone string is been found... we have found the desired element
      return !result.length;
    });
  })
  .then($el => {
    // $el is your searched element

    // some assertions about it
    expect($el.text()).not.includes("string1");
    expect($el.text()).not.includes("string2");
    expect($el.text()).not.includes("string3");
  });
  • 指定选择器以查找子项(我附加li到选择器)
  • 您使用的.not().contains是断言,而不是过滤器
  • cy.get函数返回一些 jquery 元素
  • 使用Cypress.$(即jQuery)手动过滤掉各种孩子

让我知道是否足够清楚


推荐阅读