Search code examples
testingautomationautomated-testscypressend-to-end

Get first element that does not contain value in an array in cypress


I have a list of cards and I need to programmatically select the first in the list that does not contain one of five values that I have in an array. I have tried this:

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

and this:

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

hmmm. any thoughts on this. any child element of .parent-element is fair game except for these few exceptions.


Solution

  • 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");
      });
    
    • specify the selector to find the children (I appended li to the selector)
    • the .not().contains you were using are assertions, not filters
    • the cy.get function returns some jquery elements
    • use Cypress.$ (that is jQuery) to filter out manually the various children

    Let me know if it's enough clear 😊