Cypress Get Command

2023-10-30 18:30
文章标签 get command cypress

本文主要是介绍Cypress Get Command,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

注明本文转载于:https://www.toolsqa.com/cypress/cypress-get-command/

Cypress Get Command

Cypress provides two essential methods get() and find() to search for the web elements based on the locators. The results for both of these methods are almost identical. But each has its importance and place of implementation. Subsequently, in this article, we will be covering aspects detailing where get() and find() methods which can be used during the web test automation using Cypress:

  • What is the get() command in Cypress?.
    • How to access multiple values returned by “get()” command?
    • How to chain other Cypress commands with “get()” command?
    • What is “.within()” block?
  • What is the find() command in Cypress?

 

What is the “get()” command in Cypress?

The get() method gets one or more elements based on the selector passed as a parameter. Additionally, it can return a web element or a list of web elements. After that, appropriate action can be performed on that.

Syntax:

1

cy.get(selector)

2

cy.get(selector, options)

The below image shows the syntax and various parameters which can pass to the “get” method:

 

As we can see that, the first parameter that the “get” method accepts is the “CSS selector” of the web element and the second parameter, which is an optional parameter, can take the following values:

Option

Default

Description

log

true

Toggle which enables whether the command should log on the console or not.

timeout

defaultCommandTimeout

Time for which get() should wait before raising timeout error.

withinSubject

null

Specifies from where element search should start. Additionally, null specifies that Cypress will start searching element from the root element.

 

Examples:

Get an element of type input

1

cy.get('input')

 

Specify logging as false. Moreover, it will skip the command output printing on the Cypress Test runners console.

1

cy.get('input',{ log: false })

 

Wait for an explicit timeout

1

cy.get('input',{ timeout: 1000 }) // It will wait for 1000ms before timing out

Note: cy.get() will automatically retry (default Cypress Timeout) until the element you are searching exists in DOM or until assertions you’ve chained all pass. Moreover, if it is taking more time than the default timeout, then Cypress can timeout waiting. For handling such situations, we can pass explicit timeout as an option in cy.get() command.

 

Search element within an element:

1

2

3

4

5

cy.get('input',{ withinSubject : document.querySelector('#menu-top')}) // uses jQuery Selector

 

or

 

cy.get('input',{ withinSubject : document.getElementById('#menu-top')}) // uses HTML Selector

 

How to access multiple values returned by “get()” command?

The cy.get( ) method might not return just one element. It can return a list or array of web elements, and then we have to pick certain elements and do our operations or assertions. Therefore, for handling such situations, we can use the “eq” method.

Additionally, the Eq method helps us in getting a DOM element at a specific index in an array of elements.

For example, if we have five input tags in our DOM having different values in every tag. Below is the DOM :

1

2

3

4

5

6

7

<ul>

  <input>Cypress</input>

  <input>Cucumber</input>

  <input>Gherkin</input>

  <input>JBehave</input>

  <input>BDD</input>

</ul>

Our situation is that we want to validate that if the second input tag has Cucumber in it, which it has. So we can achieve that using the eq method. Moreover, below will be our cypress command.

1

cy.get('input').eq(1).should('contain', 'Cucumber')

Note: The index value in eq starts from 0, the same as arrays in other programming languages. That is to say, the first element will be accessed using eq(0), the second element using eq(1), and so on.

How to chain other Cypress commands with “get()” command:

Another critical aspect of the “get” command is that we can chain commands to do respective actions on a particular web element. As shown in the below screenshot, the get command returns an object of the “Chainable” interface, which enables other Cypress commands to invoke on that object.

 

Cypress manages a Promise chain on your behalf, with each command returning a ‘subject’ to the next command until the chain ends or an error encounters. So, all the commands returning a chainable interface allows invoking any other Cypress command without explicitly using the “cy” object. Let’s understand this behavior with the help of the following examples:

Example:

Find the link with an “href” attribute containing the word “demoqa” and click it.

1

cy.get('a[href*="demoqa"]').click()

Find the web element with class name as ‘mobile-nav‘ and pass the timeout as options (we learned above) and then chain commands having different assertions for visibility and containing ‘Home‘ keyword.

1

2

3

cy.get('.mobile-nav', { timeout: 10000 })

  .should('be.visible')

  .and('contain', 'Home')

 

What is “.within()” block?

As we see in the above topics, we can chain Cypress commands along with other commands and assertions. In the automation world, we do come across such a situation where we want to search a web element inside a parent web element. So for doing that, we use “within” block chained with “cy.get” command to search for a particular parent element.

cy.get() always looks for the element within the whole document, with an exception that when its used inside the .within() code block. Its syntax will look like below:

Syntax:

1

2

.within(callbackFn)

.within(options, callbackFn)

Where callbackFn will be any function that will invoke after the parent function.

Let’s understand the details with the help of the following example:

1

2

3

cy.get('#searchBox').within(() => {

  cy.get('input').type('Cucumber') // Only searches inputs within searchBox

})

In this example, it will first get the “searchBox” element, and inside that searchBox element, it will search for input tags and will ignore other input tags that are not inside this. There can be a situation where we have five input tags, but we want to work on one input tag, which is under the “searchBox” element so that the situation can resolve using the “.within” block.

So, in actual, the callback function within the “.within” block is invoked after the cy.get(‘#searchBox’) function and restricts the scope of the commands inside the callback function to the scope returned by the parent get command.

 

What is the “find()” command in Cypress?

The find() method returns one or more DOM elements based on the selector that’s passed as a parameter. However, the only difference being is that the find() method always chains with other methods that return DOM elements, such as the get() method. Moreover, you can never chain/invoke the find() method on the “cy” object, as we did with the “get()” method in the previous section.

Syntax:

1

.find(selector)

2

.find(selector, options)

Below options can be passed as a parameter:

Option

Default

Description

log

true

Toggle which enables whether the command should log on the console or not.

timeout

defaultCommandTimeout

Time for which get() should wait before raising timeout error.

 

Note: As we know that find() command will always be chained on other cypress commands, we will majorly use it with the “get()” command and its syntactical representation is as follows:

1

cy.get(parentSelector).find(childSelector)

The below screenshot shows a sample invocation of find command and its various parameters and return values:

 

Let’s try to understand the usage of “find()” command with the help of the following examples:

Examples:

Consider, we do have the following HTML snapshot:

1

2

3

4

<ul id="parent">

  <li class="child"></li>

  <li class="child"></li>

</ul>

 

We have to find all the <li> elements which have the #id as “parent,” then the same can be achieved using the following command:

1

cy.get('#parent').find('li')

So, this makes it clear that, if users need to search for a web-element which is nested inside the other web-element or have a parent-child relationship, then find() will be the best fit and will provide the results quickly.

In the above code, the cy.get(‘#parent’) will do a search for the parent element only, and inside the parent web element, it will search for tags starting with “li” and will return two web elements.

Note: the log and timeout parameters have the same syntax as we used them in the “get()” command.

 

How to use get() and find() commands for automating a user scenario?

Let’s automate one user journey using get and find commands. We will continue the example from the previous article of clicking on Widget Menu Items on the “demoqa.com” to demonstrate the use of the “get()” and “find()” methods. In continuation of the clicking, let’s search all the hyperlinks or items found and assert the length of all the items found. So, let’s validate the following elements:

  • The total number of articles returned after clicking on the Widgets menu item.
  • The total number of articles that have a hyperlink value of “keyboard.”

Let’s extend the code of “cypressTest1.js” under the examples directory:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

// type definitions for Cypress object "cy"

/// <reference types="cypress" />

 

describe('My First Cypress Test', function() {

    it('Visits the ToolsQA Demo Page and check the menu items', function() {

    

   //Visit the Demo QA Website

    cy.visit("https://demoqa.com/");

    

   // Clicking on Widget Menu Item

   cy.get('#menu-top > li:nth-child(3) > a').click();

 

    //Verify number of items present on Widget Tab

    cy.get('.demo-frame > ul > li').should('have.length',19);

 

    //Verify number of items having keyboard as text on Widgets Tab

    //Get and Find Command (Parent - Child Relationship)

 

    cy.get('.demo-frame > ul > li').find('[href*=keyboard]').should('have.length',2);

    

  })

})

The following figure details the usage of “get()” (highlighted with marker 1) and “find()” (highlighted with marker 2) in the below code snippet and also the sample output of the test where the same assertions execute are highlighted with marker 1 and 2.

 

So as we have seen both in code and in the screenshot that our assertions worked fine. Additionally, we have also seen the practical implementation of “get” and “find” commands.

 

Key Takeaways

  • get() command helps in searching web elements on a web page and returns one or more elements depending on the elements matching the locator/selector passed as parameter.
  • Additionally, eq() command can access elements by index when multiple elements are returned by the get() command.
  • within() clause can be used to search for elements within the scope of other elements.
  • Moreover, find() command is also used to search for web elements on the webpage. But it can’t be directly invoked on the “cy” object. Additionally, it will always change with other cypress commands.

To conclude, we have a clear understanding of get and find commands and their practical usage. Let’s proceed to the next tutorial, where we will learn What is Asynchronous Nature of Cypress Framework?.

 

Category: CypressBy Aashish KhetarpalApril 4, 2020

注明本文转载于:https://www.toolsqa.com/cypress/cypress-get-command/

这篇关于Cypress Get Command的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/309802

相关文章

jenkins 插件执行shell命令时,提示“Command not found”处理方法

首先提示找不到“Command not found,可能我们第一反应是查看目标机器是否已支持该命令,不过如果相信能找到这里来的朋友估计遇到的跟我一样,其实目标机器是没有问题的通过一些远程工具执行shell命令是可以执行。奇怪的就是通过jenkinsSSH插件无法执行,经一番折腾各种搜索发现是jenkins没有加载/etc/profile导致。 【解决办法】: 需要在jenkins调用shell脚

10 Source-Get-Post-JsonP 网络请求

划重点 使用vue-resource.js库 进行网络请求操作POST : this.$http.post ( … )GET : this.$http.get ( … ) 小鸡炖蘑菇 <!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-w

API28_OKgo_get注意事项

1: implementation 'com.lzy.net:okgo:2.1.4' 2:在BaseApplication中onCreate()中初始化initOKgo() private void initOKgo() {//---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//HttpHeaders headers

项目一(一) HttpClient中的POST请求和GET请求

HttpClient中的POST请求和GET请求 一、HttpClient简述 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLU

apt-get update更新源时,出现“Hash Sum mismatch”问题

转载自:apt-get update更新源时,出现“Hash Sum mismatch”问题 当使用apt-get update更新源时,出现下面“Hash Sum mismatch”的报错,具体如下: root@localhost:~# apt-get update ...... ...... W: Failed to fetch http://us.archive.ubuntu.com/ub

Flutter-使用dio插件请求网络(get ,post,下载文件)

引入库:dio: ^2.1.13可直接运行的代码:包含了post,get 下载文件import 'package:flutter/material.dart';import 'package:dio/dio.dart';void main() {runApp(new MaterialApp(title: 'Container demo',home: new visitNetPage(),)

Flutter-加三方库卡在flutter package get 的解决办法

Windows PUB_HOSTED_URL ===== https://pub.flutter-io.cnFLUTTER_STORAGE_BASE_URL ===== https://storage.flutter-io.cn 增加两个环境变量,然后执行一下 flutter doctor命令。问题完美解决。

【tensorflow 使用错误】tensorflow2.0 过程中出现 Error : Failed to get convolution algorithm

如果在使用 tensorflow 过程中出现 Error : Failed to get convolution algorithm ,这是因为显卡内存被耗尽了。 解决办法: 在代码的开头加入如下两句,动态分配显存 physical_device = tf.config.experimental.list_physical_devices("GPU")tf.config.experiment

_get_gt_mask、cat_mask、_get_other_mask

import torch# 定义获取标签掩码的函数def _get_gt_mask(logits, target):print("原始 logits:\n", logits)print("目标 target:\n", target)# 将 target 拉平为一维张量target = target.reshape(-1)print("拉平后的 target:\n", target)# 创建一个和

编译时出现错误 -- clang: error: linker command failed with exit code 1 (use -v to see invocation)

出现这个错误的原因有多种,常见的是因为某些文件的缺失或者是文件的重复导致的。 这类错误查看的关键在于其上一行的文字。 对于文件缺少而导致错误的情况: 例如上图中的示例,其上一行文字为 ld:library not found for -lrxl,可以看出是缺失了某一文件而导致的错误,这行文字中的最后“ -lrxl ”:-l 代表着其前缀是“lib”,连着后面的 rxl,其名称为 libr