Kpizzle
Kpizzle

Reputation: 430

Unable To Locate And Select Item In Array

I'm learning to use cypress.io and looking to learn JavaScript at the same time.

I'm currently looking to automate an internal application for work as a proof of concept as to why we should consider switching to cypress.io instead of Webdriver.

My current issue is that I have a collection of elements that I need to loop for that contains a certain string, and select this element.

My code correctly locates all elements (located with a class), but when I try and loop through the elements looking for the one with the specific string, I'm hitting a brick wall.

Code as follow -

//Selecting profiles
cy.get('.card')
    .each(($el) => {
        if ($el.contains() === profile) {
            cy.wrap($el).click();
        }
    })

The profile variable is passed into the function that this snippet is located in.

I'm looking at the cypress documentation for .each and .contains functions.

But when I run this code I get the exception saying

TypeError: $el.contains is not a function

But looking at the cypress doc, I can attach funtions to the $el object.

.get('ul>li').each(($el, index, $list) => {
// $el is a wrapped jQuery element
if ($el.someMethod() === 'something') {
  // wrap this element so we can
  // use cypress commands on it
  cy.wrap($el).click()
} else {
  // do something else
}})

Upvotes: 2

Views: 1128

Answers (1)

Joshua Wade
Joshua Wade

Reputation: 5283

.contains() is a Cypress function. As the doc page says, $el is a jQuery-wrapped element and not a Cypress-wrapped element, so .contains() will not work on it.

That said, .contains() is used to filter a selection and will return a chainer, not a boolean or a string, so this particular way of using .contains() would not work in the first place. This is a side effect of how Cypress queues its commands - see this doc page for more info.


For what you're trying to do, I suggest taking advantage of the native jQuery element:

//Selecting profiles
cy.get('.card')
    .each(($el) => {
        if ($el.text() === profile) {
            cy.wrap($el).click();
        }
    })

Note: I'm assuming profile is a string. If it is not, this code may need to be modified.

Upvotes: 1

Related Questions