Using Cypress cy.get() with a contains selector not working as expected

Viewed 4877

I am trying to use a selector in Cypress to be able to find the data in my web page. It doesn't seem to be working as I expect, but it might just be that I'm not understanding the way it's supposed to work.

I am doing the following. The click() is just so I could see if the cy.get() worked, I'm trying to find the right selector. I will eventually be using the selector in a complex cy.contains(), I'm trying to build from the ground up.

cy.get('body:contains(ATHLETE FIRST NAME)').click();

I have an element that has the above text in two places. But the contains() above doesn't seem to be finding it, but it doesn't cause a failure.

If I change that line to:

cy.get('div:contains(ATHLETE FIRST NAME)').click();

It tells me it found that 12 times. It seems as though it is only finding the body or div, but totally ignoring the :contains(). I'm thinking I must be doing this wrong, but one example I found seems to be doing it this way, and can't find many examples at all.

==========

UPDATE 2020-06-08

I'm switching gears on this.

Here's what my code is doing, from the Cypress UI logs. I'm no longer using the :contains() selector, I'm using name instead:

contains [name=customerFirstName], johnie

Here is the element that is displayed at the time:

<input aria-invalid="false" id="outlined-name" name="customerFirstName" type="text"
       class="MuiInputBase-input MuiOutlinedInput-input" value="johnie"
       style="...">

It is not finding that value, even though it's in the element that should be selected by the name. I even tried searching on '#outlined-name', but it made no difference.

2 Answers

WRT to your update, for getting the value of an input field please see

How do I get an input’s value?

cy.get('[name=customerFirstName]')
  .should('have.value', 'johnie');

OR

cy.get('[name=customerFirstName]')
  .invoke('val')
  .should('eq', 'johnie');

The contains(selector, content) command is only for elements with content between the opening and closing tags, which is applicable to <div>, <span> etc but not <input /> which is self-closing.

:contains() is not getting ignored but cypress is considering :contains() for all the parent <div> as well. And since click event can be triggered by cypress on a single element by default you are seeing the error in the second case.

Consider this template:

<body>
  <div>
    <div>
      <div>ATHLETE FIRST NAME</div>
    </div>
  </div>
</body>

cy.get('body:contains(ATHLETE FIRST NAME)').click() will return the body element which is a single element so there will be no error.

but

cy.get('div:contains(ATHLETE FIRST NAME)').click()

will return 3 div elements so you will see this error:

cy.click() can only be called on a single element. Your subject contained 3 elements. Pass { multiple: true } if you want to serially click each element.

Related