Cypress 简明教程

Cypress - Locators

Cypress 只支持级联样式表 (CSS) 选择器来识别元素。但是,它还可以借助“Cypress-Xpath”插件来处理 xpath。

Cypress only supports the Cascading Style Sheets (CSS) selectors to identify the elements.However, it can also work with xpath, with the help of the 'Cypress-Xpath' plugin.

我们来考虑一个 html 代码片段并了解一些 css 表达式的规则。

Let us consider an html code snippet and understand some of the rules of css expression.

css expression

Rules of CSS expression

级联样式表 (CSS) 表达式的规则如下 −

The rules of Cascading Style Sheets (CSS) expression are as follows −

  1. Syntax with attribute-id and tagname is tagname#id − Here, the css expression should be -input#gsc-i-id1.

  2. Syntax with attribute-class and tagname is tagname.class − Here, the css expression should be - input.gsc-input.

  3. Syntax with any attribute value and tagname is tagname[attribute='value' − Here,the css expression should be - input[title='search'].

  4. Syntax with parent to child traversal is parent child − Here, the css expression should be -tr td.

Cypress 提供了打开选择器演练场功能,我们可以从该演练场自动定位和识别元素。此功能位于测试运行器窗口中,在下图中突出显示。

Cypress gives the feature of Open Selector Playground from which we can locate and identify elements automatically. This feature resides inside the Test Runner window which is highlighted in the below image.

test runner toolbar

单击打开选择器演练场时,一个箭头会变得可见。单击它并将其移动到我们必须识别的元素。CSS 表达式会填充在箭头右侧可用的字段 cy.get 中。

On clicking on the Open Selector Playground, an arrow gets visible. Click on it and move it to the element, which we have to identify. The css expression gets populated in the field cy.get available just to the right of the arrow.

同时,元素会突出显示,如下所示 −

Simultaneously, the element gets highlighted, as shown in the following image −

tutorialspoint scenario1