Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Cypress how to select input element based on name?

I'm starting to learn Cypress. I want to select the input field and provide the phone number by using cypress.io. The code I have following but it does not work. However can I using find or there is another way to get the input element to type in phone number?

cy.get('div').contains('Phone Number').find('input[name=teacher[0].number]').type('8000-1612023')
<div class="required field">
  <label>Phone Number</label>
  <div title="Teacher number" class="ui fluid right labeled input no-spinners">
      <input required="" type="number" name="teacher[0].number" value="">
      <div class="ui label label">US</div>
  </div>
</div>

like image 853
jacobcan118 Avatar asked Apr 16 '19 20:04

jacobcan118


3 Answers

Why don't you directly target the input field using the following code

cy.get('input[name="teacher[0].number"]').type('8000-1612023')

Please find the screenshot below for a successful test. I would also recommend you to change the type of input in your HTML to tel

HTML:

<input required="" type="tel" name="teacher[0].number" value="">

Cypress:

describe('Trial', function() {
  it('Test', function() {
    cy.visit('http://localhost:8080/trials/')
    cy.get('input[name="teacher[0].number"]').type('8000-1612023')
  })
});

Test Result:

screenshot of cypress results

like image 105
Sam Avatar answered Nov 20 '22 15:11

Sam


Try this instead:

cy.contains('div', 'Phone Number').find('input').first().type('8000-1612023')

The first argument to contains tells cypress to find the element with that selector that contains the text.

like image 21
bkucera Avatar answered Nov 20 '22 15:11

bkucera


I write selectors with the input tag as below and it worked for me.

cy.get('input[name="elementName"]').type(val)

Check this to learn best practices when selecting elements:

https://docs.cypress.io/guides/references/best-practices#Selecting-Elements

like image 2
Randi Avatar answered Nov 20 '22 15:11

Randi