乐闻世界logo
搜索文章和话题

How to select input element based on name In Cypress ?

1个答案

1

In Cypress, selecting input elements with specific names is typically done using CSS selectors. Specifically, you can use attribute selectors to select input elements based on their name attribute.

For example, if you want to select an input field with a name attribute of email, you can use the following Cypress command:

javascript
cy.get('input[name="email"]')

This line of code finds all <input> elements where the name attribute is exactly email.

Actual Application Example

Suppose we have a login form that includes username and password input fields. The HTML code is as follows:

html
<form id="login-form"> <input type="text" name="username" placeholder="Enter username"> <input type="password" name="password" placeholder="Enter password"> <button type="submit">Login</button> </form>

If you want to select the username input field in this form using Cypress, you can use:

javascript
cy.get('input[name="username"]')

Similarly, to select the password input field, you can use:

javascript
cy.get('input[name="password"]')

Performing Interactions

After selecting elements, common interactions include entering test data. For the username input field, a typical test interaction might be:

javascript
cy.get('input[name="username"]') .type('testUser');

This line of code finds the username input field and enters testUser.

By doing this, Cypress provides a very direct and powerful way to select and manipulate DOM elements, making automated testing easier and more efficient.

2024年6月29日 12:07 回复

你的答案