Cypress 简明教程
Cypress - Introduction
Cypress 是一款开源的免费自动化测试工具,从长远来看可以广泛使用。主要用于前端测试自动化。该工具主要开发用于解决团队在应用程序自动化过程中遇到的问题。
Cypress is an open-source and free test automation tool, which can be used extensively in the long run. It is mainly used for front end test automation. This tool is mainly developed to solve the issues that the teams face, while automating an application.
Cypress 有助于实现以下目标 −
Cypress helps to achieve the following −
-
Configure tests.
-
Configure tests.
-
Execute tests.
-
Identify errors (if any).
Selenium 和 Cypress 经常在功能方面进行比较。但是,Cypress 在架构和特性方面有所不同。此外,它解决了我们在 Selenium 中面临的一些问题。
Selenium and Cypress are often compared in terms of their functionalities. However, Cypress is different in architecture and features. Moreover, it resolves some of the issues we face in Selenium.
Cypress 基于 JavaScript,并在浏览器中执行测试。它有助于开发包括以下内容的测试:
Cypress is based on Javascript and executes tests within the browser. It helps to develop the tests which include −
-
Unit tests.
-
End to end tests.
-
Integration tests.
Features
Cypress 的重要特性如下所示:
The important features of Cypress are listed below −
-
Supports Test-Driven development.
-
Provides Dashboard services.
-
Efficient debugging with Developer Tools accompanied with generation of stack trace and errors.
-
Provides the screenshots for failed tests.
-
Not necessary to add waits to stop the execution for some time. By-default, the waits are applied, prior to executing the following step or assertion.
-
Able to monitor and control the characteristics of server response, functions, and timers, which are essentially needed for unit testing.
-
Check and manage network traffic.
-
Allows the multi-browser support.
-
In-built feature to capture videos of execution is available.
-
Can be integrated with continuous integration tools.
-
Page responsiveness with viewport sizing.
-
Reloads changes applied to tests by default.
-
Friendly Application Programming Interfaces (APIs) are available.
-
Test runner available, which allows the test execution straight from the User Interface (UI).
Disadvantages
使用 Cypress 会有一些缺点,如下所示:
There are some disadvantages of using Cypress and they are listed below −
-
It is only based on JavaScript.
-
A relatively new tool and hence, the community support is not extensive.
-
It cannot perform mobile testing.
-
Shadow Document Object Model (DOM) cannot be accessed.
-
Tabs/child windows are managed by workarounds.
Cypress - Architecture and Environment Setup
Cypress 架构如下图所示 −
Cypress architecture is illustrated in the below diagram −
The source of the above diagram is https://www.tutorialspoint.com/cypress-architecturetest-automation
Selenium 等自动化工具通过在浏览器外部运行来工作。然而,Cypress 具有不同的架构。它在浏览器内部运行。Cypress 基本上基于服务器。Node.js。
Automation tools like Selenium work by running outside the browser. However, the Cypress has a different architecture. It runs within the browser. Cypress is basically based on the server - Node.js.
Cypress 与 Node.js 有着持续的交互,它们相互协调地工作。因此,Cypress 可用于测试应用程序的前端和后端。
There is a continued interaction of Cypress with the Node.js and they work in coordination with each other. As a result, Cypress can be utilised for testing both the front and backend of the application.
如此,Cypress 既能够处理在 UI 上进行的实时任务,同时还能够执行浏览器外部的动作。
Cypress is thus, capable of handling the tasks performed at a real time on the UI and simultaneously can also perform the actions outside of the browser.
Difference between Cypress and Selenium
Cypress 与 Selenium 之间的基本区别如下所列 −
The basic differences between Cypress and Selenium are listed below −
Cypress |
Selenium |
It is based on Javascript. |
It is based on Java, C#, Python and JavaScript. |
It has small community support |
It has big community support. |
It includes an in-built video capture feature. |
There is no in-built video capture feature. |
No APIs are available to handle the tabs/child windows. |
APIs available to handle tabs/child windows. |
No parallel execution can be performed. |
Parallel execution can be performed. |
Only installation of npm needed. |
Supplemental Jars, libraries, and so on are required to be added as project dependencies. |
Cypress Environment Setup
有关 Cypress 环境设置,请访问链接-@ {s12}。将出现的屏幕如下所示 -
For Cypress environment setup, visit the link −https://nodejs.org/en/download/. The screen that will appear is given below −
将同时提供 Windows 和 macOS 安装程序。我们必须根据本地操作系统获取软件包。
There shall be both Windows and macOS Installer. We have to get the package as per the local operating system.
对于 64 位 Windows 配置,会弹出以下窗口提示保存安装程序。
For a 64- bit Windows configuration, the following pop-up comes up to save the installer.
安装完成后,程序文件中将创建一个 nodejs 文件。记下该文件的路径。然后,如下所示从“开始”处输入环境变量 −
Once the installation is done, a nodejs file gets created in the Program files. The path of this file should be noted. Then, enter environment variables from the Start, as shown below −
在“系统属性”弹出窗口中,转到“高级”,单击“环境变量”。然后单击确定。
In the System Properties pop-up, move to Advanced, click on Environment Variables. Then click on OK.
在“环境变量”弹出窗口中,转到“系统变量”部分并单击“新建”。
In the Environment Variables pop-up, move to the System variables section and click on New.
在“新建系统变量”弹出窗口中,分别在“变量名”和“变量值”字段中输入 NODE_HOME 和 node.js 路径(前面已记录)。
Enter NODE_HOME and the node.js path (noted earlier) in the Variable name and the Variable value fields respectively in the New System Variable pop-up.
设置 node.js 文件的路径后,我们将在任何所需位置创建一个空文件夹(比如 cypressautomation)。
Once the path of the node.js file is set, we shall create an empty folder (say cypressautomation) in any desired location.
接下来,我们需要一个 JavaScript 编辑器来编写 Cypress 的代码。为此,我们可以从链接 [role="bare"] [role="bare"]https://code.visualstudio.com/ 下载 Visual Studio Code。
Next, we need to have a JavaScript editor to write the code for Cypress. For this, we can download Visual Studio Code from the link [role="bare"]https://code.visualstudio.com/
根据本地操作系统选择正确的包 −
As per the local operating system, choose the correct package −
下载可执行文件并完成所有安装步骤后,Visual Studio Code 将启动。
Once the executable file is downloaded, and all the installation steps are completed, the Visual Studio Code gets launched.
从“文件”菜单中选择“打开文件夹”选项。然后,将 CypressAutomation 文件夹(我们之前创建的)添加到 Visual Studio Code。
Select the option Open Folder from the File menu. Then, add the CypressAutomation folder (that we have created before) to the Visual Studio Code.
我们需要使用以下命令从终端创建 package.json 文件 −
We need to create the package.json file with the below command from terminal −
我们必须输入包名称、描述等详细信息,如下面给出的图像中所示 −
We have to enter details like the package name, description, and so on, as mentioned in the image given below −
npm init
完成后,package.json 文件将使用我们提供的信息在项目文件夹中创建。
Once done, the package.json file gets created within the project folder with the information we have provided.
完成后,package.json 文件将使用我们提供的信息在项目文件夹中创建。
Once done, the package.json file gets created within the project folder with the information we have provided.
最终,要安装 Cypress,运行下面给出的命令 -
Finally, to install Cypress run the command given below −
npm install cypress --save-dev
你将获得以下输出 -
You will get the following output −
Cypress - Test Runner
Cypress Test Runner 有助于触发测试执行。当我们完成 Cypress 安装后,该工具在终端上提出了建议,如下所示 -
Cypress Test Runner helps to trigger the test execution. As we complete Cypress installation, there comes a suggestion from the tool on the terminal, as mentioned below −
You can open Cypress by running − node_modules/.bin/cypress open
要打开 Test Runner,我们必须运行下面提到的命令 -
To open the Test Runner, we have to run the below mentioned command −
node_modules/.bin/cypress open
一段时间后,“测试运行器”窗口将打开,显示一条消息,即 Cypress 在 examples 文件夹中提供了示例项目文件夹结构。
The Test Runner window opens up after some time with the message that a sample project folder structure has been provided by Cypress under examples folder.
单击“确定,我知道了!”按钮。然后,计算机上将显示如下屏幕:
Click on the OK, got it! button. The screen that will appear on your computer would be as follows −
然后,测试运行器将启动,其中 examples 文件夹下提供了一个以上的 spec 文件,如下所示:
Then the Test Runner is launched, with the more than one spec files available under the examples folder, as stated below −
要运行特定文件,例如 test2.spec.js,我们必须单击它。此外,还提供了浏览器和停止执行的选项。
To run a specific file, for example, test2.spec.js, we have to click it. Also, the browser and the option to Stop the execution are available.
执行应当从以下屏幕开始,显示测试步骤、测试用例名称、测试套件、URL、测试持续时间、浏览器尺寸,等等。
The execution shall begin with the following screen showing the test steps, name of test case, test suite, URL, test duration, dimension of browser, and so on.
Cypress - Build First Test
一旦 Cypress 配置完毕,就会在项目内创建一个框架,该框架在 Explorer 中自动可见。新的测试文件(比如 FirstTest.spec.js)应在 integration 文件夹中创建,如下所示。
Once Cypress has been configured, a framework gets created within the project which is automatically visible in the Explorer. The new test file (say FirstTest.spec.js) should be created within the integration folder, as mentioned below.
Cypress Folder Structure
让我们了解 Cypress 中的文件结构。Cypress 文件夹中包含的因素如下所述:
Let us understand the folder structure in Cypress. The factors that are included in a Cypress folder are explained below −
-
fixtures − Test data in form of key-value pairs for the tests are maintained here.
-
integration − Test cases for the framework are maintained here.
-
plugins − Cypress events (prior and post events to be executed for a test) are maintained here.
-
support − Reusable methods or customized commands, which can be utilised by test cases directly, without object creation are created here.
-
videos − Executed test steps are recorded in the form of videos and maintained here.
-
node_modules − Project dependencies from the npm are maintained in this folder.It is the heart of the Cypress project execution.
-
cypress.json − Default configurations are set in this folder. The values of the current configurations can be modified here, which overrules the default configurations.
-
package.json − Dependencies and scripts for the projects are maintained in this folder.
Structure of a Basic Test
Cypress 遵循 JavaScript 测试框架(Mocha、Jasmine 等)。要在 Cypress 中创建测试,我们必须遵守以下框架准则:
Cypress follows the JavaScript test frameworks (Mocha, Jasmine, and so on). To create a test in Cypress, we have to adhere to the below mentioned framework guidelines −
-
Test suite name has to be provided within the describe function.
-
Test case names within a test suite have to be provided within the same or you have to specify the function.
-
Test steps within a test case have to be implemented inside the it/specify block.
Basic Test Implementation
基本的测试执行可以通过使用如下命令完成:
The basic test implementation can be done by using the following command −
// test suite name
describe('Tutorialspoint Test', function () {
// Test case
it('Scenario 1', function (){
// test step for URL launching
cy.visit("https://www.google.com/");
});
});
上面使用的cy命令不需要对象调用。它在默认安装节点模块时是可用的。
The cy command used above does not require an object invocation. It becomes available by default on installing the node modules.
Test Execution
对于执行 from the command line ,运行下面给出的命令:
For execution from the command line, run the command given below −
./node_modules/.bin/cypress run
这里,集成文件夹内的所有文件都会被触发。
Here, all the files within the integration folder get triggered.
对于执行 from the Test Runner ,运行下面给出的命令:
For execution from the Test Runner, run the command stated below −
./node_modules/.bin/cypress open
然后,点击我们要触发执行的说明文件。
Then, click on the spec file that we want to trigger for execution.
要触发执行 for a specific file from command line ,运行下面给出的命令:
To trigger execution for a specific file from command line, run the command mentioned below −
cypress run --spec "<spec file path>"
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
Cypress - Supported Browsers
Cypress可以在Chrome、Electron和Firefox等浏览器中运行测试。在测试运行器中,我们可以在右上角选择浏览器。
Cypress can run tests in browsers like Chrome, Electron, and Firefox. In the Test Runner,we have the option to choose the browser from the right upper corner.
另外,必须注意的是,如果浏览器选项不可用,这意味着我们的系统中没有最新版本的浏览器。
Also, it must be noted that if a browser option is not available, it means we do not have the latest version of that browser in our system.
Execution from Other Browsers
下面解释了从命令行从其他浏览器执行:
The execution from other browsers from Command Line is explained below −
要运行 execution in Chrome ,您需要运行下面提到的命令:
To run the execution in Chrome, you need to run the below mentioned command −
./node_modules/.bin/cypress run -- browser chrome
您会看到以下画面:
You can see the following screen −
要运行 execution in Firefox ,运行下面给出的命令:
To run the execution in Firefox, run the command given below −
./node_modules/.bin/cypress run -- browser firefox
您会看到以下画面:
You can see the following screen −
要运行 execution in headed mode ,运行下面给出的命令:
To run the execution in headed mode, run the command given below −
./node_modules/.bin/cypress run -- headed
从命令行,如果未指定选项,Cypress将在无头模式下执行测试。
From the command line, Cypress executes tests in headless mode, if no option is specified.
Cypress - Basic Commands
基本的Cypress命令如下:
Cypress basic commands are listed below −
and
它用于创建断言,是.should()的别名。
It is used to create an assertion and is an alias of .should ().
用法如下:
The usage is as follows −
//element is visible & enabled
cy.get('#txt').should('be.visible').and('be.enabled')
//element is checked
cy.contains('Subject').and('be.checked')
as
它提供了别名以便以后使用。
It provides an alias for later usage.
用法如下:
The usage is as follows −
//alias element as parent
cy.get('#txt').find('li').first().as('parent')
blur
它模糊焦点中元素。
It blurs an element in focus.
用法如下:
The usage is as follows −
//blur input
cy.get('#txt'). type('abc').blur()
check
它选中单选按钮或复选框,并应用于拥有 input 标签的元素。
It checks radio buttons or checkboxes and is applied to elements having input tags.
用法如下:
The usage is as follows −
//checks element having class attribute chkbox
cy.get('.chkbox').check()
children
它获得元素的子元素。
It obtains the sub elements of an element.
用法如下:
The usage is as follows −
//obtains children of element n
cy.get('n').children()
clear
它从 textarea 或 input 中删除值。
It removes the value from textarea or input.
用法如下:
The usage is as follows −
//removes input abc
cy.get('#txt'). type('abc').clear()
clearCookie
它删除特定的浏览器 cookie。
It removes a particular browser cookie.
用法如下:
The usage is as follows −
//clear abc cookie
cy.clearCookie('abc')
clearCookies
它从现有域和子域中删除浏览器 cookie。
It removes the browser cookies from an existing domain and subdomain.
用法如下:
The usage is as follows −
//clear all cookies
cy.clearCookies()
clearLocalStorage
它从现有域和子域中删除本地存储数据。
It removes the local Storage data from an existing domain and subdomain.
用法如下:
The usage is as follows −
//clear all local storage
cy. clearLocalStorage ()
click
它点击 Document Object Model (DOM) 中的元素。
It clicks an element in Document Object Model (DOM).
用法如下:
The usage is as follows −
//click on element with id txt
cy.get('#txt').click()
contains
它获得具有特定文本的元素。元素可以拥有比文本更多内容并且仍然匹配。
It obtains an element having a specific text. The element can have more than the text and still match.
用法如下:
The usage is as follows −
//returns element in #txt having Tutor text
cy.get('#txt').contains('Tutor')
dblclick
它双击 Document Object Model (DOM) 中的元素。
It double-clicks an element in Document Object Model (DOM).
用法如下:
The usage is as follows −
//double clicks element with id txt
cy.get('#txt').dblclick()
debug
它修复调试器,并由先前命令返回日志值。
It fixes a debugger and log values are returned by prior command.
用法如下:
The usage is as follows −
//pause to debug at start of command
cy.get('#txt').debug()
document
它在活动页面上获得 window.document。
It obtains window.document on the active page.
用法如下:
The usage is as follows −
cy.document()
each
它遍历具有 length 属性的数组。
It iterates through an array having the property length.
用法如下:
The usage is as follows −
//iterate through individual li
cy.get('li').each(() => {...})
end
它结束命令链。
It ends a command chain.
用法如下:
The usage is as follows −
//obtain null instead of input
cy.contains('input').end()
eq
它引用元素数组中特定索引处的元素。
It refers to an element at a particular index in an array of elements.
用法如下:
The usage is as follows −
//obtain third td in tr
cy.get('tr>td').eq(2)
find
它获得特定定位器的后代元素。
It obtains the descendant elements of a particular locator.
用法如下:
The usage is as follows −
//obtain td from tr
cy.get('tr').find('td')
first
它从一组元素中获取第一个元素。
It obtains the first element from a group of elements.
用法如下:
The usage is as follows −
//obtain first td in tr
cy.get('tr>td').first()
get
它通过定位器获取单个或多个元素。
It obtains single or multiple elements by locator.
用法如下:
The usage is as follows −
//obtain td from tr
find
它获得特定定位器的后代元素。
It obtains the descendant elements of a particular locator.
用法如下:
The usage is as follows −
//obtain all td from tr in list
cy.get('tr>td')
getCookie
它通过名称获取特定浏览器 cookie。
It obtains a particular browser cookie by its name.
用法如下:
The usage is as follows −
cy.getCookie('abc')
go
在浏览器历史记录中向前或向后移动到下一个或上一个 URL。
It moves forward or backward to the next or previous URL in browser history.
用法如下:
The usage is as follows −
//like clicking back button
cy.go('back')
//like clicking forward button
cy.go('forward')
visit
它启动一个 URL。
It launches an URL.
用法如下:
The usage is as follows −
cy.visit('https://www.tutorialspoint.com/index.htm')
next
它获取文档对象模型 (DOM) 中元素组中元素的直接同级元素。
It obtains the immediate sibling of an element within a group of elements in Document Object Model (DOM).
用法如下:
The usage is as follows −
//gives the following link in element l.
cy.get('l a:first').next()
parent
它从 DOM 中元素组中获取父元素。
It obtains the parent element from a group of elements in DOM.
用法如下:
The usage is as follows −
//get parent of element with class h
cy.get('.h').parent()
should
它用于创建断言,是 .and() 的别名。
It is used to create an assertion and is an alias of .and ().
用法如下:
The usage is as follows −
//assert element is visible & enabled
cy.get('#txt').should('be.visible').and('be.enabled')
wait
在执行下一步之前,以毫秒为单位或以别名元素等待一段时间。
Wait for a certain time in milliseconds or for an aliased element prior to moving the following step.
用法如下:
The usage is as follows −
cy.wait(1000)
title
它获取活动页面的 document.title。
It obtains the document.title of the active page.
用法如下:
The usage is as follows −
cy.title()
viewport
它管理屏幕的尺寸和定位。
It manages the dimension and positioning of the screen.
用法如下:
The usage is as follows −
// viewport to 100px and 500px
cy.viewport(100, 500)
Cypress - Variables
在 Cypress 中,使用了诸如 var、let 和 const 这样的变量。在使用闭包时,我们可以使用未经分配获得的对象。但是,当我们使用可变对象时,情况并非如此。
In Cypress, there is usage of variables like var, let, and const. While working with closures,we can use the objects that were obtained without assignment. But, this is not the case,when we are working with mutable objects.
当一个对象修改其特性时,我们可能需要将它的之前值与新值进行比较。
When an object modifies its characteristics, we may need to compare its prior value to its new value.
Code Implementation
我们可使用下面提到的命令来实现代码 −
We can do the code implementation by using the below mentioned command −
cy.get('.btn').then(($span) => {
// value capture before button click and stored in const
const n = parseInt($span.text())
cy.get('b').click().then(() => {
// value capture after button click and stored in const
const m = parseInt($span.text())
// comparison
expect(n).to.eq(m)
})
})
在上述情况下,我们使用 const 变量,因为对象 $span 正在发生变化。在处理可变对象及其值时,建议使用类型为 const 的变量。
In the above case, we are using const variables since object $span is undergoing change. While dealing with mutable objects and its value, it is recommended to use variables of type const.
Cypress - Aliases
Cypress 别名是一个重要的组件,有多种用途。这些用途如下所列 −
Cypress aliases are an important component that have multiple uses. These uses are listed below −
Sharing Context
我们必须使用 .as() 来标记我们必须共享的内容。要标记对象和基元,Mocha 上下文对象被使用。可以用 this.* 访问别名对象。
We have to use .as() to alias something that we have to share. To alias objects and primitives, Mocha context objects are used. The alias object can be accessed with this.*.
默认情况下,Mocha 为适用于测试的所有钩子共享上下文,并清除测试执行后的别名属性。
Mocha by default, shares context for all the hooks applicable for the test and the alias properties are flushed post the execution of a test.
describe('element', () => {
beforeEach(() => {
cy.wrap('eleone').as('x')
})
context('subelement', () => {
beforeEach(() => {
cy.wrap('eletwo').as('y')
})
it('aliases properties', function () {
expect(this.x).to.eq(' eleone ')
expect(this.y).to.eq(' eleone ')
})
})
})
})
我们可以通过共享上下文来处理固定装置。我们还可以使用异步命令 cy.get(),通过 @ 符号(而不是使用 this.*)来访问别名。这是一个同步命令。
We can handle fixtures by sharing context. We can also use cy.get(), which is an asynchronous command, to access an alias with the help of @ symbol (instead of using this.*) This is a synchronous command.
beforeEach(() => {
// alias fixtures
cy.fixture('users.json').as('u')
})
it('scenario', function () {
// '@' to handle aliases
cy.get('@u').then((u) => {
// access element argument
const i = u[0]
//verification
cy.get('header').should('contain', u.name)
})
})
Elements
别名可以与文档对象模型(DOM)元素一起使用,并随后被重新使用。在下面的示例中,默认情况下,Cypress 会引用获得的 td 集合作为别名 cols。要使用相同的 cols,我们必须使用 cy.get() 命令。
Alias can be used with Document Object Model (DOM) elements and later be reused. Here in the below example, by default Cypress makes a reference to td collection obtained as the alias cols. To use the same cols, we have to use cy.get() command.
// alias td in tr
cy.get('tr').find('td').as('cols')
cy.get('@cols').first().click()
因为我们在 cy.get() 中使用了 @,所以 Cypress 搜索当前的别名 (cols) 并生成它的引用。
As we used @ in cy.get(), Cypress searches for the present alias (cols) and yields its reference.
Routes
别名可以与路由一起使用。它确保应用程序发起了请求。然后,它等待服务器的响应并访问请求进行验证。
Aliases can be utilised with routes. It makes sure that the application has made the requests. Then, it awaits a response from the server and accesses the request for verification.
cy.intercept('POST', '/users', { id: 54 }).as('u')
cy.get('#btn').click()
cy.wait('@u').then(({ request }) =>{
//assertion
expect(request.body).to.have.property('name', 'User')
})
cy.contains('User added')
Requests
别名可以与请求一起使用。我们可以标记一个请求并稍后使用它的属性。这可以按如下方式完成 −
Aliases can be utilised with requests. We can alias a request and later use its properties.This can be done as follows −
cy.request('https://jsonplaceholder.cypress.io/comments').as('c')
// other implementations if any
cy.get('@c').should((response) => {
if (response.status === 404) {
// assertion
expect(response).to.have.property('duration')
} else {
// do something else
}
})
})
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.
Rules of CSS expression
级联样式表 (CSS) 表达式的规则如下 −
The rules of Cascading Style Sheets (CSS) expression are as follows −
-
Syntax with attribute-id and tagname is tagname#id − Here, the css expression should be -input#gsc-i-id1.
-
Syntax with attribute-class and tagname is tagname.class − Here, the css expression should be - input.gsc-input.
-
Syntax with any attribute value and tagname is tagname[attribute='value' − Here,the css expression should be - input[title='search'].
-
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.
单击打开选择器演练场时,一个箭头会变得可见。单击它并将其移动到我们必须识别的元素。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 −
Cypress - Assertions
Cypress 拥有多种断言类型,这些类型来自不同的库,例如 Mocha、Chai 等等。断言类型分为显式和隐式。
Cypress has more than one type of assertions obtained from various libraries like Mocha,Chai, and so on. The assertion types are explicit and implicit.
Implicit Assertions
如果一个断言适用于链中从父命令获取的对象,则称为隐式断言。流行的隐式断言包括 .and/.should。
If an assertion is applicable to the object obtained from the parent command in a chain, it is known as the implicit assertion. The popular implicit assertions include .and/.should.
这些命令不能作为独立命令使用。通常,当我们必须对特定对象执行多个检查时,我们使用它们。
These commands cannot be used as standalone. Generally, they are used when we have to verify multiple checks on a particular object.
让我们通过下面的示例来说明隐式断言 −
Let us illustrate implicit assertion with an example given below −
// test suite
describe('Tutorialspoint', function () {
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://www.tutorialspoint.com/videotutorials/index.php")
// assertion to validate count of sub-elements and class attribute value
cy.get('.toc chapters').find('li').should('have.length',5)
.and('have.class', 'dropdown')
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
输出日志显示了使用 should 和命令获得的两个断言。
The output logs show two assertions obtained with should, and commands.
Explicit Assertions
如果一个断言适用于对象本身,则称为显式断言。流行的显式断言包括 assert/expect。
If an assertion is applicable to an object directly, it is known as the explicit assertion. The popular explicit assertions include assert/expect.
用于显式断言的命令如下 −
The command for explicit assertion is as follows −
// test suite
describe('Tutorialspoint', function () {
// it function to identify test
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://accounts.google.com")
// identify element
cy.get('h1#headingText').find('span').then(function(e){
const t = e.text()
// assertion expect
expect(t).to.contains('Sign')
})
})
})
Execution Results
Execution Results
输出如下 −
The output is given below −
输出日志显示了使用 expect 命令直接应用于对象的断言。
The output logs show assertions directly applied to objects with the expect command.
Cypress 拥有默认断言,这些断言在内部处理,不需要专门调用。
Cypress has Default Assertions which are internally handled and do not require to be invoked specifically.
以下是一些示例 −
Few examples are as follows −
-
cy.visit () − Expects the page to show the content with 200 status code.
-
cy.request () − Expects the remote server to be available and sends a response.
-
cy.contains () − Expects the web element with its properties to be available in DOM.
-
cy.get () − Expects the web element to be available in DOM.
-
.find () − Expects the web element to be available in DOM.
-
.type () − Expects the web element to turn to a type able state.
-
.click () − Expects the web element to turn to a clickable state.
-
.its () − Expects for a web element property on the existing subject.
Other Cypress assertions
其他 Cypress 断言如下:
The other Cypress assertions are as follows −
length
It 检查从先前链接命令中获得的元素的计数。
It checks the count of elements obtained from the previously chained command.
例如,
For example,
cy.get('#txt-fld').should('have.length',5)
value
It 检查 Web 元素是否具有某个值。
It checks whether the web element has a certain value.
例如,
For example,
cy.get('#txt-fld').should('have.length',5)
value
It 检查 Web 元素是否具有某个值。
It checks whether the web element has a certain value.
例如,
For example,
cy.get(' #txt-fld').should('have.value', 'Cypress')
class
It 检查 Web 元素是否具有某个 class。
It checks whether the web element possesses a certain class.
例如,
For example,
cy.get('#txt-fld'').should('have.class', 'txt')
contain
It 检查 Web 元素是否具有某个文本。
It checks whether the web element possesses a certain text.
例如,
For example,
cy.get('#txt-fld'').should('contain', 'Cypress')
visible
It 检查 Web 元素是否可见。
It checks whether the web element is visible.
例如,
For example,
cy.get('#txt-fld'').should('be.visible')
Cypress - Text Verification
text 方法可用于获取 web 元素的文本。还可以添加断言来验证文本内容。
The method text can be used to obtain text of a webelement. Assertions can also be added to verify the text content.
Implementation with text()
以下是有关文本验证的 text() 实施命令:
Given below is the command for the implementation with text() with regards to verification −
// test suite
describe('Tutorialspoint', function () {
// it function to identify test
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://accounts.google.com")
// identify element
cy.get('h1#headingText').find('span').then(function(e){
//method text to obtain text content
const t = e.text()
expect(t).to.contains('Sign')
})
})
})
Execution Results
Execution Results
输出如下 −
The output is as follows −
输出日志显示使用 text 方法获得的 SignIn 文本。
The output logs show the text Sign in obtained with the text method.
Implementation with text assertions
我们还可以借助以下命令在 web 元素文本上实现断言:
We can also implement assertions on web element text with the help of the following command −
// test suite
describe('Tutorialspoint', function () {
// it function to identify test
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://accounts.google.com")
// verify text with have.text
cy.get('h1#headingText').find('span').should('have.text','Sign in')
})
})
Execution Results
Execution Results
输出如下:
The output is mentioned below −
输出日志显示使用 should 断言完成的文本验证。
The output logs show the text verification done with should assertion.
Cypress - Asynchronous Behavior
Cypress 源自 node.js,后者基于 JavaScript。Cypress 命令本质上是同步的,因为它们依赖于 node 服务器。异步流意味着测试步骤在执行时不依赖于其先前的步骤。
Cypress is derived from node.js, which is based on JavaScript. Cypress commands are synchronous in nature, since they are dependent on node server. Asynchronous flow means that the test step does not depend on its prior step for execution.
没有依赖,每个步骤都作为独立的标识符执行。尽管测试步骤按顺序排列,但单个测试步骤不考虑前一步骤的结果,而仅仅执行自身。
There is no dependency and each of the steps is executed as a standalone identity. Though the test steps are arranged in a sequence, an individual test step does not consider the outcome of the previous step and simply executes itself.
Example
以下是在 Cypress 中异步行为的一个示例:
Following is an example of asynchronous behavior in Cypress −
// test suite
describe('Tutorialspoint', function () {
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://accounts.google.com")
// identify element
cy.get('h1#headingText').find('span').should('have.text', 'Sign in')
cy.get('h1#headingText').find('span').then(function(e){
const t = e.text()
// get in Console
console.log(t)
})
// Console message
console.log("Tutorialspoint-Cypress")
})
})
Execution Results
Execution Results
输出如下 −
The output is given below −
Promise
右键单击测试运行器,然后单击 Inspect,我们可以在控制台验证结果。此处, Tutorialspoint-Cypress (先前的步骤)在控制台登录,早于 Sign – in (稍后添加的步骤)。
Right-click on Test Runner and click on Inspect, and we can verify results in the Console.Here, Tutorialspoint-Cypress (an earlier step) is logged in the Console before Sign – in (step added later).
Cypress 命令的设计方式是按照顺序执行每一步,而不是同时触发它们。但是,它们按顺序排列。因此,它使得流变得同步。这是通过 Promise 实现的。
Cypress commands are designed in such a way that every step is executed in sequence and they are not triggered simultaneously. But, they are lined up one behind another.Thereby, it makes the flow as synchronous. This is achieved with Promise.
在上面的示例中, console.log 是一个纯 JavaScript 语句。它没有像 Cypress 命令那样排队等待的能力。Promise 使我们可以以串行模式执行 Cypress 命令。
In the above example, console.log is a pure JavaScript statement. It does not have the ability to line up and wait similar to Cypress commands. Promise allows us to execute Cypress commands in a serial mode.
Modes in Promise
Promise 有三种模式来对命令执行的状态进行分类。它们如下:
A Promise has three modes to categorise the state of a command execution. They are as follows −
-
Resolved − This outcome occurs, if the test step runs successfully.
-
Pending − This is the outcome, if the test step run result is being awaited.
-
Rejected − This is the outcome, if the test step runs unsuccessfully.
仅在先前的步骤已成功执行或收到解析后的 promise 响应后,才会执行 Cypress 命令。然后,该方法用于在 Cypress 中实现 Promise。
A Cypress command gets executed, only if the prior step has been executed successfully or a resolved promise response is received. Then, the method is used to implement Promise in Cypress.
Example
以下是在 Cypress 中 Promise 的示例:
Following is an example of Promise in Cypress −
describe('Tutorialspoint Test', function () {
it('Promise', function (){
return cy.visit('https://accounts.google.com')
.then(() => {
return cy.get('h1#heading');
})
})
})
Cypress 对 Promise 的实现是封装的,不可见的。因此,这有助于获得更紧凑的代码。此外,在自动化测试时,我们不必考虑 Promise 的状态。
Cypress implementation for Promise is encapsulated and not visible. Thus, it helps to have a more compact code. Also, we do not have to consider the state of Promise, while automating the tests.
Implementation without Promise
以下命令解释了如何在 Cypress 中在没有 promise 的情况下完成实现:
Following command explains how an implementation can be done without promise in Cypress −
describe('Tutorialspoint Test', function () {
it('Without Promise', function (){
cy.visit('https://accounts.google.com')
cy.get('h1#heading')
})
})
Cypress - Working with XHR
XHR 是 XML HTTP Request。它是一个应用程序编程接口 (API),可用作对象,其方法在 Web 浏览器和服务器之间发送数据。XHR 中的对象可以请求以响应形式从服务器请求数据。
XHR is XML HTTP Request. It is an Application Programming Interface (API) which is available as an object, whose methods send data between a web browser and server. An object in XHR can request data from a server in the form of a response.
Cypress 不仅可以用于前端自动化,还可以通过直接访问 XHR 对象来控制网络流量。然后,它对该对象应用断言。它可以模拟或伪造响应。可以在浏览器的网络选项卡中查看 XHR 详细信息。
Cypress can not only be used for front end automation, but also can control the network traffic by directly accessing the XHR objects. Then, it applies the assertions on the objects.It can mock or stub a response. An XHR details can be seen in the Network tab in the browser.
XHR 响应头的语法如下:
XHR response Header is as follows −
响应如下:
The response is as follows −
可以使用 cy.request() 命令执行 XHR 请求。cy.intercept() 方法用于将响应重定向到匹配的请求。
To make an XHR request, the cy.request() command is used. The method cy.intercept() is used to redirect the responses to the matching requests.
Implementation of XHR request
以下命令用于解释 XHR 请求在 Cypress 中的实现——
Given below is the command to explain the implementation of XHR request in Cypress −
cy.request('https://jsonplaceholder.cypress.io/comments').as('c')
//aliasing request
cy.get('@c').should((response) => {
expect(response.body).to.have.length(100)
expect(response).to.have.property('headers')
})
Cypress - jQuery
Cypress 不仅可以使用 get 方法来识别 Web 元素,还可以使用 JQuery 的对象及其方法以及其内部命令。虽然 Cypress 使用 get 方法来识别 Web 元素,但是 JQuery 使用 $() 方法用于相同目的。
Cypress can act upon jQuery objects and its methods along with its internal commands.While Cypress uses the get method to identify a web element, JQuery uses the $() method for the same purpose.
在 Cypress 中,用于识别 Web 元素的命令如下所示——
In Cypress, the command for identifying a web element is as follows −
cy.get('h1#heading')
而在 JQuery 中,用于识别 Web 元素的命令如下所示——
Whereas in case of jQuery, the command for identification of a web element is as follows −
$('h1#heading')
Cypress 是基于异步特征的 JavaScript。但是,Cypress 命令通过在内部解析 Promise(最终用户不可见)同步执行。
Cypress is based on JavaScript which is of asynchronous nature. However, Cypress commands behave synchronously by resolving the Promise internally, which is hidden from the end user.
但是,当 Cypress 对 JQuery 对象及其方法执行操作时,必须明确地实现 Promise 逻辑,以使得流程同步(借助方法 then)。
Nevertheless, when Cypress acts upon jQuery objects and its methods, the Promise logic has to be implemented specifically, to make flow synchronous (with the help of method then).
例如,当我们想要提取 Web 元素的文本内容(使用 JQuery 方法 - text)时,我们需要使用 then 方法实现 Promise。
For instance, while we want to extract the text content of a web element (with jQuery method - text), we require to implement Promise with the then method.
Promise Implementation in jQuery
以下是 JQuery 中 Promise Cypress 实现的命令——
Following is the command for the Promise Cypress implementation in jQuery −
// test suite
describe('Tutorialspoint', function () {
// it function to identify test
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://accounts.google.com")
// Promise implementation with then()
cy.get('h1#headingText').find('span').then(function(e){
//method text to obtain text content
const t = e.text()
expect(t).to.contains('Sign')
})
})
})
在 JQuery 中,如果提供的定位符与 DOM 中的任何 Web 元素不匹配,则返回一个空集合。
In jQuery, an empty collection is returned, if the locator which is provided, does not match with any of the web elements in DOM.
为了避免异常,建议验证 $() 产生的 JQuery 集合的长度。命令如下所示——
In order to avoid exceptions, it is recommended to verify the length of the jQuery collection yielded by $(). The command for the same is as follows −
const e = $('#txt')
if (e.length > 0){
//proceed
}
但是,如果 DOM 中没有匹配的 Web 元素,则 Cypress 会自动转到重试模式,直到元素可用或超时,如下所示——
However, in case, there are no matching web elements in DOM, the Cypress automatically goes to the retry mode till the element is available or there is a timeout, as shown below −
cy.get('#txt')
.then((e) => { //proceed working on element })
该方法会产生一个 Promise。此外,只有当一个 Web 元素与定位符匹配时,该 Promise 才处于已解决模式。如果 Promise 处于拒绝状态,则 then 块中的逻辑将永远不会执行。
The method yields a Promise. Also, the Promise shall be in resolved mode, only if a web element is matched with the locator. If the Promise is in a reject state, the logic within the then block will never be executed.
我们可以在 Cypress 中通过以下表达式访问 JQuery 方法——
We can access jQuery methods in Cypress, with the following expression −
Cypress.$( '#txt'), where #txt is the locator.
Implementation of jQuery methods
以下是使用 JQuery 在 Cypress 中识别和执行测试的命令——
Given below is a command for the identification and execution of the test in Cypress with jQuery −
// test suite
describe('Tutorialspoint', function () {
// it function to identify test
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://accounts.google.com")
// access web element with Cypress.$
cy.request('/').get('h1#headingText').then(function(e){
Cypress.$(e).find('span')
const t = e.text()
cy.log(t)
})
})
})
当执行上述测试时,如果我们打开控制台(按下 F12)并使用表达式 Cypress.$ ('h1#headingText').text() 查找必需的 Web 元素,我们可以验证测试,如下所示——
As the above test is executed, if we open the Console (pressing F12), and find for the required web element, with the expression Cypress.$ ('h1#headingText').text(), we can verify our test, as shown below −
日志消息——登录——是从 Cypress 中的 cy.log 命令获得的。
The log message – Sign –in is obtained from the cy.log command in Cypress.
Cypress - Checkbox
检查和取消检查命令用于处理复选框。在 html 代码中,复选框有一个 input 标签,其 type 属性的值为 checkbox。
The commands check and uncheck are used to work with checkbox. In the html code, a checkbox has an input tag and its type attribute has the value as checkbox.
Cypress Commands
与复选框相关的 Cypress 命令如下所示——
The checkbox related Cypress commands is as follows −
-
The command used to click all the checkboxes is as follows −
cy.get('input[type="checkbox"]').check()
-
The command used to click a checkbox with id check is as follows −
cy.get('#chk').check()
-
The command used to click a checkbox with value Cypress is as follows −
cy.get('input[type="checkbox"]').check('Cypress')
-
The command used to click the checkboxes with values - Java and Python is as follows −
cy.get('input[type="checkbox"]').check(['Java','Python'])
-
The command used to click the checkbox having value Java with options is as follows −
cy.get('.chk').check('Java', options)
-
The command used to click the checkboxes with values – Java and Python with options is as follows:
cy.get('input[type="checkbox"]').check(['Java','Python'], options)
-
The command used to click the checkbox having class check with an option is as follows −
cy.get('.chk').check({force : true})
-
The command used to uncheck all the checkboxes is as follows −
cy.get('input[type="checkbox"]').uncheck()
-
The command used to uncheck a checkbox with id check is as follows −
cy.get('#chk').uncheck()
-
The command used to uncheck the checkbox with value Cypress is as follows −
cy.get('input[type="checkbox"]').uncheck('Cypress')
-
The command used to uncheck the checkboxes with values - Java and Python is as follows −
cy.get('input[type="checkbox"]').uncheck(['Java','Python'])
-
The command used to uncheck the checkbox having value Java with options is as follows −
cy.get('.chk').uncheck('Java', options)
-
The command used to uncheck the checkboxes with values – Java and Python with options is as follows −
cy.get('input[type="checkbox"]').uncheck(['Java','Python'], options)
-
The command used to uncheck the checkbox having class check with an option is as follows −
cy.get('.chk').uncheck({force : true)
Options in Cypress
Cypress 中可用的选项如下:
The options which are available in Cypress are as follows −
-
log – Default value – true − This is used to turn on/off console log.
-
timeout – Default value – defaultCommandTimeout(4000ms) − This is used to provide the maximum wait time prior to throwing an error.
-
force – Default value – false − This is used to enforce an action.
-
scrollBehaviour – Default value – scrollBehaviour(top) − This is for the position of viewport up to which element to be scrolled prior command execution.
-
waitForAnimations – Default value – waitForAnimations(true) − This is used to wait for elements to complete animation prior running the commands.
-
animationDistanceThreshold - Default value – animationDistanceThreshold (5) − This is for the pixel distance of an element that should be exceeded to qualify for animation.
勾选/取消勾选命令都要求与产生 DOM 元素的命令串联,而且可以将断言应用于这些命令。
Both check/uncheck commands require to be chained with commands that yield DOM elements and assertions can be applied to these commands.
Implementation of Cypress Commands
Cypress 中命令的实现如下所述−
The implementation of the commands in Cypress is explained below −
// test suite
describe('Tutorialspoint', function () {
// it function to identify test
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://accounts.google.com/signup")
//checkbox with assertion
cy.get('input[type="checkbox"]').check().should('be.checked')
//identify checkbox with class with assertion
cy.get('.VfPpkd-muHVFf-bMcfAe').uncheck().should('not.be.checked')
})
})
Execution Results
Execution Results
输出如下:
The output is mentioned below −
上述结果显示“显示密码”左侧的复选框,首先使用 check 命令选中(使用断言应进行验证)。
The above results show the checkbox to the left of the Show password, first getting checked with the check command (verified with assertion-should).
然后,使用 uncheck 命令取消选中(也使用断言应进行验证)。
Then, it is unchecked with the uncheck command (also verified with assertion-should).
Cypress - Tabs
Cypress 没有处理选项卡的具体命令。它在 jQuery 中有一个解决方法,通过它处理选项卡。在 html 代码中,由于 target 特性,链接或按钮会打开新选项卡。
Cypress does not have a specific command to work with tabs. It has a workaround method in jQuery through which it handles the tabs. In the html code, a link or button opens to a new tab, because of the attribute target.
如果 target 特性具有空白值,它会打开新选项卡。Cypress 使用 jQuery 方法 removeAttr,它由 invoke 命令调用。removeAttr 删除特性,该特性作为 invoke 方法的参数之一传递。
If the target attribute has value blank, it opens to a new tab. Cypress uses the jQuery method removeAttr, which is invoked by the invoke command. The removeAttr deletes the attribute, which is passed as one of the parameters to the invoke method.
一旦删除 target=blank,链接/按钮就会在父窗口中打开。稍后,对其执行操作之后,我们可以使用 go 命令返回父 URL。
Once the target=blank is removed, then a link/button opens in the parent window. Later on after performing the operations on it, we can shift back to the parent URL with the go command.
为此,Html 代码如下:
The Html code for the same is as follows −
Implementation
下面是有关 Cypress 中选项卡的命令实现:
Given below is the implementation of the use of commands with regards to tabs in Cypress −
describe('Tutorialspoint', function () {
// test case
it('Scenario 1', function (){
// url launch
cy.visit("https://the-internet.herokuapp.com/windows")
// delete target attribute with invoke for link
cy.get('.example > a')
.invoke('removeAttr', 'target').click()
// verify tab url
cy.url()
.should('include', 'https://the-internet.herokuapp.com/windows/new')
// shift to parent window
cy.go('back');
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
输出日志显示在父窗口中删除了 target 特性并启动了新选项卡。
The output logs show the deletion of the target attribute and launch of the new tab within the parent window.
Cypress - Dropdown
select 命令用于处理静态下拉列表。在 html 代码中,下拉列表具有 select 标记,下拉列表元素通过 option 标记名表示。
The command select is used to work with static dropdown. In the html code, a dropdown has a select tag and the dropdown elements are represented by option tagname.
Dropdown Cypress Commands
与下拉列表相关的 Cypress 命令如下所示:
The dropdown related Cypress commands are as follows −
-
The command used to choose the option Cypress is as follows −
cy.get('select').select('Cypress')
-
The command that chooses options Tutorialspoint and JavaScript is as follows −
cy.get('select').select(['Tutorialspoint', 'JavaScript'])
-
The command which can choose a value of a dropdown option along with options (to modify default characteristics) is as follows −
cy.get('select').select('option1', options )
-
The command that chooses the multiple values with options is as follows −
cy.get('select').select(['option1', 'option2'], options)
Options for dropdown in Cypress
Cypress 中可用于下拉列表的选项如下所示:
The options which are available for the dropdown in Cypress are as follows −
-
log – Default value – true− This is used to turn on/off the console log.
-
timeout – Default value – defaultCommandTimeout(4000)− This is used to provide the maximum wait time for the selection prior to throwing an error.
-
force – Default value – false− This is used to enforce an action.
断言可以应用于 Cypress 中的 select 命令。
Assertion can be applied to the select commands in Cypress.
让我们尝试从下拉列表中选择选项 India ,该选项在 html 代码中的值为 99。
Let us make an attempt to select the option India from the dropdown having value as 99 in the html code.
Implementation
在 Cypress 中选择选项印度的下拉命令实现如下所示:
The implementation of the dropdown commands to select the option India in Cypress is explained below −
// test suite
describe('Tutorialspoint', function () {
// it function to identify test
it('Scenario 1', function (){
// test step to launch a URL
cy.visit("https://register.rediff.com/register/register.php")
//select option India with value then verify with assertion
cy.get('select[id="country"]').select('99').should('have.value', '99')
})
})
Execution Results
Execution Results
输出如下 −
The output is stated below −
输出显示 Country 下拉列表选择选项 India(在 html 代码中,该选项的值标识为 99)。
The output shows that the Country dropdown selects the option India (in the html code, this option is identified with the value as 99).
Cypress - Alerts
Cypress 可以在缺省情况下处理警报。弹出窗口可能是警报或确认弹出窗口。Cypress 的设计方式是这样的,始终在弹出窗口中单击“确定”按钮。此外,Cypress 还有触发浏览器事件的能力。
Cypress can work with alerts by default. The pop-up can be an alert or confirmation popup.Cypress is designed in such a way that it shall always click on the OK button on the pop-up. Moreover, Cypress has the ability to fire the browser events.
警报由 window:alert event 触发。这在缺省情况下由 Cypress 处理,并且在执行过程中警报中的“确定”按钮被单击,且未显示。
An alert is triggered by window:alert event. This is by default handled by Cypress and the OK button on the alert gets clicked, without being visible during execution.
但是,执行日志将显示该警报的存在。
However, the execution logs will show the presence of the alert.
Implementation Alerts
Cypress 中警报的实现如下−
The implementation of alerts in Cypress is given below −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch url
cy.visit("https://register.rediff.com/register/register.php");
// click submit
cy.get('input[type="submit"]').click();
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
警报信息显示在 Cypress 执行日志中。
The alert message gets displayed on the Cypress execution logs.
Cypress 有通过使用 on 方法触发 window:alert 事件的能力。然后,我们可以验证警报文本。
Cypress has the ability to fire the window:alert event by utilising the method on. Then, we can verify the alert text.
但是,此事件将在后端发生,并且在执行过程中不会显示。
However, this event shall happen in the back end and will not be visible during the execution.
Implementation Alert text verification
以下是 Cypress 中警报文本验证的实现−
Given below is the implementation for the alert text verification in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch url
cy.visit("https://register.rediff.com/register/register.php");
// click submit
cy.get('input[type="submit"]').click();
// fire event with method on
cy.on('window:alert',(t)=>{
//assertions
expect(t).to.contains('Your full name');
})
});
});
Execution Results
Execution Results
输出如下:
The output is mentioned below −
输出日志显示成功验证了警报文本,该警报是由 Cypress 触发的警报事件产生的。
The output logs show the successful verification of the alert text, produced by firing the alert event by Cypress.
对于确认弹出窗口,触发浏览器事件 window:confirm。就像警报弹出窗口一样,Cypress 可以使用 on 方法触发此事件,并且在缺省情况下单击“确定”按钮。
For a confirmation pop-up, the browser event window:confirm is triggered. Just like alert pop-ups, Cypress can fire this event with the method on and clicks on the OK button by default.
Example
我们来看一下下面的示例。在此,单击“单击以获取 JS 确认”按钮时,会显示确认弹出窗口。
Let us have a look at the below example. Here, on clicking the Click for JS Confirm button, a confirmation pop up gets displayed.
显示包含按钮 OK 和 Cancel 的以下确认弹出窗口。
The following confirmation pop-up with OK and Cancel buttons getting displayed.
单击“确定”按钮后,显示以下内容−
On clicking the OK button, the following is displayed −
You clicked: Ok
将显示一个如下图所示的图像 −
An image like the one given below will be displayed −
点击 Cancel 按钮时,Result − 下方会显示以下内容:
On clicking the Cancel button, the following is displayed below Result −
You clicked: Cancel
将显示一个如下图所示的图像 −
An image like the one given below will be displayed −
Implementation Confirmation verification
以下给出了 cypress 中警报确认验证的实现:
Given below is an implementation for the confirmation verification of alerts in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it("Scenario 1", function () {
//URL launched
cy.visit("https://the-internet.herokuapp.com/javascript_alerts")
//fire confirm browser event and accept
cy.get(':nth-child(2) > button').click()
cy.on("window:confirm", (t) => {
//verify text on pop-up
expect(t).to.equal("I am a JS Confirm");
});
});
});
Execution Results
Execution Results
输出如下 −
The output is stated below −
Implementation Confirmation verification
以下给出了 cypress 中警报确认验证的实现:
Given below is an implementation for the confirmation verification of alerts in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it("Scenario 1", function () {
//URL launched
cy.visit("https://the-internet.herokuapp.com/javascript_alerts")
//fire confirm browser event and accept
cy.get(':nth-child(2) > button').click()
cy.on("window:confirm", (t) => {
//verify text on pop-up
expect(t).to.equal("I am a JS Confirm");
});
});
});
Execution Results
Execution Results
输出如下 −
The output is stated below −
输出日志显示成功验证确认文本,该文本是通过 cypress 激发的确认事件产生的。
The output logs show the successful verification of the confirmation text, produced by firing the confirm event by Cypress.
Implementation Cancel click
在 cypress 中取消确认弹出窗口点击的实现如下:
The implementation of cancel click on confirmation pop up in Cypress is as follows −
describe('Tutorialspoint Test', function () {
// test case
it("Scenario 1", function () {
// URL launched
cy.visit("https://the-internet.herokuapp.com/javascript_alerts")
//fire confirm browser event
cy.on("window:confirm", (s) => {
return false;
});
// click on Click for JS Confirm button
cy.get(':nth-child(2) > button').click()
// verify application message on Cancel button click
cy.get('#result').should('have.text', 'You clicked: Cancel')
});
});
Execution Results
Execution Results
输出如下 −
The output is given below −
输出日志显示成功验证标签 You clicked: Cancel ,该标签是通过点击确认弹出窗口上的取消按钮产生的。
The output logs show the successful verification of the text You clicked: Cancel, which is produced on clicking the Cancel button on the confirmation pop up.
Cypress - Child Windows
Cypress 没有特定命令来处理子窗口。它有一个 jQuery 的解决方法,通过该方法来处理子窗口。在 HTML 代码中,由于属性目标,一个链接或按钮会打开到子窗口。
Cypress does not have a specific command to work with child windows. It has a workaround method in jQuery through which it handles the child windows. In the html code, a link or button opens to a child window, because of the attribute target.
如果目标属性值为 blank,它会打开到子窗口。Cypress 使用 jQuery 方法 removeAttr,该方法由 cypress 中的 invoke 命令调用。removeAttribute 删除属性,该属性作为参数之一传递给 invoke 方法。
If the target attribute has value blank, it opens to a child window. Cypress uses the jQuery method removeAttr, which is invoked by the invoke command in Cypress. The removeAttr deletes the attribute, which is passed as one of the parameters to the invoke method.
移除 target=blank 后,一个链接/按钮会在父窗口中打开,并在其上执行操作后,我们可以用 go 命令切换回父 URL。
Once the target=blank is removed, then a link/button opens in the parent window and after performing operations on it, we can shift back to the parent URL with the go command.
在 Cypress 中打开子窗口的 html 代码如下:
The Html code for opening a child window in Cypress is as follows −
Implementation
下面给出了 cypress 中子窗口命令的实现:
Given below is an implementation of the commands for child windows in Cypress −
describe('Tutorialspoint', function () {
// test case
it('Scenario 1', function (){
// url launch
cy.visit("https://the-internet.herokuapp.com/windows")
// delete target attribute with invoke for link
cy.get('.example > a')
.invoke('removeAttr', 'target').click()
// verify child window url
cy.url()
.should('include', 'https://the-internet.herokuapp.com/windows/new')
// shift to parent window
cy.go('back');
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
输出日志显示移除目标属性并启动父窗口中的子窗口。
The output logs show the deletion of the target attribute and launching of the child window within the parent window.
Cypress - Hidden Elements
Cypress 可以处理隐藏元素。有时,只在鼠标悬停在主菜单上时才显示子菜单。这些子菜单最初被 Cascading Style Sheets (CSS) 属性 display:none 隐藏。
Cypress can handle the hidden elements. There are occasions, when the submenus get displayed only on hovering over the main menu. These submenus are initially made hidden with the Cascading Style Sheets (CSS) property display:none.
为了处理这些隐藏元素,Cypress 借助于 jQuery 方法 show。必须利用 Cypress 命令 (invoke['show']) 来调用它。
For handling the hidden elements, Cypress takes the help of the jQuery method show. It has to be invoked with the help of the Cypress command (invoke['show']).
例如,鼠标悬停在登录菜单上时,登录按钮将显示,如下所示:
For example, on hovering over the Sign in menu, the Sign in button gets displayed, as shown below −
当鼠标移出登录菜单时,登录按钮将隐藏,如下所示:
On moving the mouse out of the Sign in menu, the Sign in button gets hidden, as displayed below −
Implementation
使用 jQuery show 方法处理隐藏元素的实现如下:
The implementation of the hidden elements with jQuery show method is as follows −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch URL
cy.visit("https://www.amazon.com/");
// show hidden element with invoke
cy.get('#nav-flyout-ya-signin').invoke('show');
//click hidden element
cy.contains('Sign').click();
});
});
Execution Results
Execution Results
输出如下 −
The output is given below −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch URL
cy.visit("https://www.amazon.com/");
// show hidden element with invoke
cy.get('#nav-flyout-ya-signin').invoke('show');
//click hidden element
cy.contains('Sign').click();
});
});
Execution Results
输出如下 −
The output is given below −
执行日志显示步骤右侧图标表示的隐藏元素。
The execution logs show the hidden elements represented by an icon at the right of the steps.
Cypress 有另一种处理隐藏元素的技术。
Cypress has another technique for handling hidden elements.
例如,为了点击隐藏元素,我们可以使用 Cypress 命令 click 并将选项 {force : true} 作为参数传递给它 - click({ force: true })。
For example, to click a hidden element we can use the Cypress command click and pass the option {force : true} as a parameter to it - click({ force: true }).
这会修改隐藏元素的隐藏特征,我们就可以点击它了。
This modifies the hidden characteristics of the hidden element and we can click it.
Implementation with click
下面给出了 Cypress 中包含 click 选项的实现:
Given below is the implementation with click having option in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch URL
cy.visit("https://www.amazon.com/");
//click hidden element
cy.contains('Sign').click({force:true});
});
});
Execution Results
Execution Results
输出如下:
The output is mentioned below −
执行日志显示隐藏元素已点击(Sign in),并且我们已导航到下一页。
The execution logs show the hidden element clicked (Sign in) and we are navigated to the next page.
Cypress - Frames
早期版本的 Cypress 无法访问框架中的元素。但是,最近的版本有针对框架的解决方案。
The earlier versions of Cypress were unable to access the elements inside frames. But, the recent versions have a solution for frame.
要使用框架,首先,我们必须使用以下命令安装 Cypress 插件:
To work with frames, first, we have to install a Cypress plugin with the command given below −
npm install –D cypress-iframe
将显示的屏幕如下所示:
The screen which will be displayed is given below −
对于 Cypress 中的框架实现,我们必须在代码中添加语句*import ‘cypressiframe’*。标签名 frame/iframe 用于表示 HTML 代码中的框架。
For the frame implementation in Cypress, we have to add the statement *import 'cypressiframe'*in the code. A tagname called frame/iframe is used to represent frames in the html code.
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
Cypress 命令 frameload 用于将焦点从主页移到框架。一旦焦点转移,我们就可以与框架内的元素进行交互。
Cypress command frameload is used to move the focus from the main page to the frame.Once the focus is shifted, we can interact with the elements inside the frame.
这是通过 cy.iframe 方法完成的。
This is done with the cy.iframe method.
Implementation
下面通过使用 cy.iframe 方法给出了 Cypress 框架命令的实现:
Given below is the implementation of the Cypress command for frames, by using the cy.iframe method −
import 'cypress-iframe'
describe('Tutorialspoint Test', function () {
// test case
it('Test Case6', function (){
// launch URL
cy.visit("https://jqueryui.com/draggable/");
// frame loading
cy.frameLoaded('.demo-frame');
//shifting focus
cy.iframe().find("#draggable").then(function(t){
const frmtxt = t.text()
//assertion to verify text
expect(frmtxt).to.contains('Drag me around');
cy.log(frmtxt);
})
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
执行日志显示了在框架中访问的元素以及其中获取的文本。
The execution logs show the accessing elements inside a frame and the text grabbed within it.
Cypress 无法处理页面中的多个框架。
Cypress cannot handle more than one frame in a page.
此外,对于 Cypress 中的 Frame Intellisense,我们可以将 /// <reference types = "Cypressiframe"/> 添加到代码中。
Also, for frame Intellisense to Cypress, we can add /// <reference types = "Cypressiframe"/> to the code.
Cypress - Web Tables
Cypress 能够处理网络表格。表格基本上有两种类型,动态和静态。静态表格与动态表格不同,它具有固定数量的列和行。
Cypress is capable of handling the web tables. A table is basically of two types, which are dynamic and static. A static table has a fixed number of columns and rows unlike a dynamic table.
在 html 代码中,表格由表标记名表示,而行由 tr 表示,列由 td 表示。
In an html code, a table is represented by table tagname, while rows are represented by tr, and columns by td.
-
To access the rows, the Cypress command is as follows −
cy.get("tr")
-
To access the columns, the Cypress command is as follows −
cy.get("td") or cy.get("tr td")
-
To access a particular column, the CSS expression should be as follows −
td:nth-child(column number)
-
To iterate through the rows/columns of the table, the Cypress command each is used.
在 Cypress 中,我们有命令 next 至 shift to the immediate following sibling element 。此命令必须与 get 命令链接。prev 命令用于移到紧邻的前一个同级元素。
In Cypress, we have the command next to shift to the immediate following sibling element. This command has to be chained with get command. The command prev is used to shift to the immediate preceding sibling element.
表格的 Html 结构如下所示:
The Html structure of a table is given below −
Example
让我们举一个表格的示例,并验证与第一列 AUTOMATION TOOL 中的值 Selenium 相对应的第二列 TYPE(Open Source)的内容。
Let us take an example of a table, and verify the content of the second column TYPE (Open Source) corresponding to the value Selenium, which is in the first column AUTOMATION TOOL.
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
Implementation
下面是与表格相关的 Cypress 命令的实现:
Given below is the implementation of the Cypress commands related to tables −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
//URL launch
cy.visit("https://sqengineer.com/practice-sites/practice-tables-selenium/")
// identify first column
cy.get('#table1> tbody > tr > td:nth-child(1)').each(($elm, index, $list)=> {
// text captured from column1
const t = $elm.text();
// matching criteria
if (t.includes('Selenium')){
// next sibling captured
cy.get('#table1 > tbody > tr > td:nth-child(1)')
.eq(index).next().then(function(d) {
// text of following sibling
const r = d.text()
//assertion
expect(r).to.contains('Commercial');
})
}
})
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
执行日志显示 TYPE 列中的值被捕获为 Open Source。发生这种情况是因为它是与元素 Selenium(第一列)紧邻的后一个同级元素,并且出现在同一行中。
The execution logs show that the value in the column TYPE is captured as Open Source.This happens as it is the immediate following sibling to the element Selenium (first column)which appears in the same row.
Cypress - Mouse Actions
Cypress 可以处理隐藏元素。有时只有在将鼠标悬停在主菜单上时才会显示子菜单。这些子菜单最初使用 CSS 属性 display:none 制成隐藏状态。
Cypress can handle hidden elements. There are occasions when submenus get displayed only on hovering over the main menu. These submenus are initially made hidden with the CSS property display:none.
为了处理隐藏元素,Cypress 使用 jQuery 方法 show。它必须在 Cypress 命令(invoke['show'])的帮助下调用。
For handling hidden elements, Cypress takes the help of the jQuery method show. It has to be invoked with the help of the Cypress command (invoke['show']).
例如,将鼠标悬停在“Mouse Hover”按钮上时,Top 和 Reload 按钮会显示,如下所示:
For example, on hovering over the Mouse Hover button, the Top and Reload buttons get displayed, as shown below −
将鼠标移出“Mouse Hover”按钮时,Top 和 Reload 按钮会隐藏,如下所示:
On moving the mouse out of the Mouse Hover button, the Top and Reload buttons get hidden, as shown below −
Implementation with jQuery show method
下面是 Cypress 中使用 jQuery show 方法的实现:
Given below is the implementation with jQuery show method in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch URL
cy.visit("https://learn.letskodeit.com/p/practice");
// show hidden element with invoke
cy.get('div.mouse-hover-content').invoke('show');
//click hidden element
cy.contains('Top').click();
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
执行日志显示隐藏元素——步骤右侧图标表示的顶部按钮。
The execution logs show the hidden element – Top button represented by an icon at the right of the steps.
Cypress - Cookies
Cypress 使用方法 Cookies.preserveOnce() 和 Cookies.defaults() 处理 Cookies。如果 Cookies 有任何更改,方法 Cookies.debug() 会在控制台生成日志。
Cypress handles cookies with the methods Cookies.preserveOnce() and Cookies.defaults(). The method Cookies.debug() produces logs to the console, if there are any changes to the cookies.
默认情况下,Cypress 会在每次测试执行前删除所有 Cookie。我们可以利用 Cypress.Cookies.preserveOnce() 来保留 Cookies 及其名称,以便在其他测试中使用。
By default, Cypress removes all cookies prior to each test execution.We can utilise Cypress.Cookies.preserveOnce() to preserve the cookies with their names to be used for other tests.
Syntax
在 Cypress 中用于与 Cookie 相关的命令的语法如下所示:
The syntax for the commands related to the cookies in Cypress are as follows −
这将在配置或清除 Cookie 值时生成控制台日志。
This will produce console logs, if cookie values are configured or cleared.
Cypress.Cookies.debug(enable, option)
在此,
Here,
-
enable – if debug of cookie should be enabled.
-
option – configure default values for cookies, for example, preserve cookies.
Cypress.Cookies.debug(true) // logs will generate if cookies are modified
cy.clearCookie('cookie1')
cy.setCookie('cookie2', 'val')
降低日志记录的级别。
To reduce the level of logging.
Cypress.Cookies.debug(true, { verbose: false })
Cypress.Cookies.debug(false) // logs will not generate if cookies are modified
下面给出的语法将保留 Cookies,并且在执行其他测试之前不会清除它们。
The syntax given below will preserve the cookies and they will not be cleared prior execution of another test.
Cypress.Cookies.preserveOnce(cookie names...)
此语法用于修改全局配置并维护为测试保留的一组 Cookie。任何修改都将适用于该特定测试(保留在 cypress/support/index.js 文件中并在测试执行前加载)。
This syntax is used to modify global configuration and to maintain a group of cookies that are preserved for a test. Any modification will be applicable for that particular test.(maintained in cypress/support/index.js file and are loaded prior to test execution).
Cypress.Cookies.defaults(option)
Cypress.Cookies.defaults({
preserve: 'cookie1'
})
此处,不会在运行测试前清除名为 cookie1 的 Cookie。
Here, the cookie named cookie1 will not be cleared before running the test.
Cookie Methods
Cypress 中的一些 Cookie 方法如下:
Some of the cookie methods in Cypress are as follows −
-
cy.clearCookies() − It removes all the cookies from present domain and subdomain.
-
cy.clearCookie(name) − It removes a cookie from the browser by name.
-
cy.getCookie(name) − It is used to obtain a cookie from the browser by name.
-
cy.getCookies() − It is used to obtain all the cookies.
-
cy.setCookie(name) − It can configure a cookie.
Implementation
下面给出了在 Cypress 中 Cookie 方法的实现:
Given below is the implementation of the cookie methods in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch the application
cy.visit("https://accounts.google.com");
// enable cookie logging
Cypress.Cookies.debug(true)
//set cookie
cy.setCookie('cookie1', 'value1')
//get cookie by name and verify value
cy.getCookie('cookie1').should('have.property', 'value', 'value1')
//clear cookie by name
cy.clearCookie('cookie')
//get all cookies
cy.getCookies()
//clear all cookies
cy.clearCookies()
//verify no cookies
cy.getCookies().should('be.empty')
});
});
Execution Results
Execution Results
输出如下:
The output is mentioned below −
Cypress - Get and Post
Get 和 Post 方法是应用程序编程接口 (API) 测试的一部分,可由 Cypress 执行。
The Get and Post methods are a part of the Application Programming Interface (API) testing, which can be performed by Cypress.
Get Method
要执行 Get 操作,我们将用 cy.request() 发出 HTTP 请求,并将方法 Get 和 URL 作为参数传递给该方法。
To perform a Get operation, we shall make a HTTP request with the cy.request() and pass the method Get and URL as parameters to that method.
状态代码反映了请求是否已被正确接受和处理。代码 200(表示确定)和 201(表示已创建)。
The status code reflects, if the request has been accepted and handled correctly. The code 200(means ok) and 201(means created).
Implementation of Get
Get 方法在 Cypress 中的实现如下所示:
The implementation of Get method in Cypress is explained below −
describe("Get Method", function(){
it("Scenario 2", function(){
cy.request("GET", "https://jsonplaceholder.cypress.io/comments", {
}).then((r) => {
expect(r.status).to.eq(200)
expect(r).to.have.property('headers')
expect(r).to.have.property('duration')
});
})
})
Execution Results
Execution Results
输出如下 −
The output is as follows −
Post Method
在使用 Post 方法时,我们实际上正在发送信息。如果我们有一组实体,借助 Post,我们可以在末尾附加新的实体。
While using the Post method, we are actually sending information. If we have a group of entities, we can append new ones at the end, with the help of Post.
为了执行一个 Post 操作,我们将使用 cy.request() 创建一个 HTTP 请求,并将方法 Post 和 URL 作为参数传递给那个方法。
To perform a Post operation, we shall make a HTTP request with the cy.request() and pass the method Post and URL as parameters to that method.
Implementation of Post
下面提供了 Post 方法在 Cypress 中的一个实现:
Given below is an implementation of Post method in Cypress −
describe("Post Method", function(){
it("Scenario 3", function(){
cy.request('https://jsonplaceholder.cypress.io/users?_limit=1')
.its('body.0') // yields the first element of the returned list
// make a new post on behalf of the user
cy.request('POST', 'https://jsonplaceholder.cypress.io/posts', {
title: 'Cypress',
body: 'Automation Tool',
})
})
});
Execution Results
Execution Results
输出如下 −
The output is given below −
Cypress - File Upload
要在 Cypress 中执行文件上传任务,我们必须首先使用下面提到的命令安装一个插件:
To perform file upload task in Cypress, we have to first install a plugin with the command mentioned below −
npm install –dev cypress-file-upload
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
安装完成后,我们必须在 command.js 文件中添加语句 import 'cypress-file-upload'。此文件位于 Cypress 项目中 support 文件夹内。
Once the installation is done, we have to add the statement import 'cypress-file-upload' in the command.js file. This file resides inside the support folder within our Cypress project.
另外,我们还应将要上传到 fixtures 文件夹(Picture.png 文件)中的文件添加在内。将显示以下屏幕 −
Also, we shall add the file that we want to upload within the fixtures folder (Picture.png file). The following screen will be displayed −
要上传文件,我们必须使用 Cypress 命令 attachFile,并将要上传的文件路径作为参数传递给它。
To upload a file, we have to use the Cypress command, attachFile and pass the path of the file to be uploaded as a parameter to it.
Implementation
在 Cypress 中上传文件的命令实现方式如下 −
The implementation of the commands for uploading a file in Cypress is as follows −
describe('Tutorialspoint Test', function () {
// test case
it('Test Case6', function (){
//file to be uploaded path in project folder
const p = 'Picture.png'
// launch URL
cy.visit("https://the-internet.herokuapp.com/upload")
//upload file with attachFile
cy.get('#file-upload').attachFile(p)
//click on upload
cy.get('#file-submit').click()
//verify uploaded file
cy.get('#uploaded-files').contains('Picture')
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
执行日志显示,Picture.png 文件已上传,文件名称已反映在页面上。
The execution logs show that the file Picture.png got uploaded and the file name got reflected on the page.
Cypress - Data Driven Testing
Cypress 数据驱动测试借助 fixtures 得以实现。Cypress fixtures 被添加到维护和保存自动化测试数据中。
Cypress data driven testing is achieved with the help of fixtures. Cypress fixtures are added to maintain and hold the test data for automation.
fixtures 保存在 Cypress 项目中的 fixtures 文件夹(example.json 文件)中。它基本上帮助我们从外部文件获取数据输入。
The fixtures are kept inside the fixtures folder (example.json file) in the Cypress project.Basically, it helps us to get data input from external files.
Cypress fixtures 文件夹可以有 JavaScript 对象表示法 (JSON) 或其他格式的文件,并且数据以“键: 值”对进行维护。
Cypress fixtures folder can have files in JavaScript Object Notation (JSON) or other formats and the data is maintained in "key:value" pairs.
所有测试数据都可以被多个测试使用。所有固定数据都必须在 before 钩子块内声明。
All the test data can be utilised by more than one test. All fixture data has to be declared within the before hook block.
Syntax
Cypress 数据驱动的测试语法如下所示:
The syntax for Cypress data driven testing is as follows −
cy.fixture(path of test data)
cy.fixture(path of test data, encoding type)
cy.fixture(path of test data, opts)
cy.fixture(path of test data, encoding type, options)
在此,
Here,
-
path of test data is the path of test data file within fixtures folder.
-
encoding type − Encoding type (utf-8, asci, and so on) is used to read the file.
-
Opts − Modifies the timeout for response. The default value is 30000ms. The wait time for cy.fixture(), prior throws an exception.
Implementation in example.json
下面给出在 Cypress 中使用 example.json 进行数据驱动测试的实现:
Given below is the implementation of data driven testing with example.json in Cypress −
{
"email": "abctest@gmail.com",
"password": "Test@123"
}
Implementation of Actual Test
在 Cypress 中实际进行数据驱动测试的实现如下:
The implementation of actual data driven testing in Cypress is as follows −
describe('Tutorialspoint Test', function () {
//part of before hook
before(function(){
//access fixture data
cy.fixture('example').then(function(signInData){
this.signInData = signInData
})
})
// test case
it('Test Case1', function (){
// launch URL
cy.visit("https://www.linkedin.com/")
//data driven from fixture
cy.get('#session_key ')
.type(this.signInData.email)
cy.get('# session_password').type(this.signInData.password)
});
});
Execution Results
Execution Results
输出如下:
The output is as follows
输出日志显示值 abctest@gmail.com 和 Test@123 分别输入到“电子邮件”和“密码”字段。这些数据已从固定数据传递到测试。
The output logs show the values abctest@gmail.com and Test@123 being fed to the Email and Password fields respectively. These data have been passed to the test from the fixtures.
Cypress - Prompt Pop-up Window
Cypress 可以处理提示弹出窗口,用户可以在其中输入值。提示有一个文本字段,其中输入是采用。要处理提示弹出窗口,请使用 cy.window() 方法。
Cypress can handle prompt pop-up windows, where users can input values. A prompt has a text field, where the input is taken. To handle a prompt pop-up, cy.window() method is used.
获取提示符对象的值(远程窗口)。在确认/警告弹出窗口中,我们必须触发浏览器事件。但对于提示弹出窗口,我们必须使用 cy.stub() 方法。
It obtains the value of the object of the prompt (remote window). In a confirmation/alert pop-up, we have to fire a browser event. But for prompt pop-up, we have to use cy.stub() method.
Example
让我们看一下下面的示例,单击单击 JS 提示按钮时,会显示一个提示弹出窗口,如下所示−
Let us look at the below example, on clicking the Click for JS Prompt button, a prompt pop up gets displayed, as shown below −
随即显示带用户输入字段的提示。如您所见,Tutorialspoint 已输入在提示弹出窗口中,如下所示。
The following prompt with the user input field gets displayed. Tutorialspoint is entered in the prompt pop-up, as shown below.
您输入的 − Tutorialspoint 显示在结果下方。
You entered − Tutorialspoint gets displayed under Result.
您可以在以下所示的屏幕中看到这一点−
This can be seen in the screen displayed below −
Implementation
下面是 Cypress 中用于显示提示弹出窗口的命令的实现 −
Given below is an implementation of the commands for displaying prompt pop-up windows in Cypress −
describe('Tutorialspoint Test', function () {
// test case
it("Scenario 1", function () {
//URL launch
cy.visit("https://the-internet.herokuapp.com/javascript_alerts")
//handling prompt alert
cy.window().then(function(p){
//stubbing prompt window
cy.stub(p, "prompt").returns("Tutorialspoint");
// click on Click for JS Prompt button
cy.get(':nth-child(3) > button').click()
// verify application message on clicking on OK
cy.get('#result').contains('You entered: Tutorialspoint')
});
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
输出日志显示成功验证了文本内容。
The output logs show the successful verification of the text.
You entered − Tutorialspoint ,是单击提示弹出窗口中的确定按钮时产生的。另外,应用于提示窗口的存根在输出日志中可见。
You entered − Tutorialspoint, is produced on clicking OK button on prompt pop up. Also, the stub applied on the prompt window is visible on the output log.
Cypress - Dashboards
必须设置Cypress Dashboard服务,才能创建运行在我们系统中的Cypress测试与托管在云中的控制面板之间的链接。
Cypress Dashboard Service has to be set up to create a link between Cypress tests running in our system and the dashboard which is hosted on the cloud.
Features
Cypress Dashboard的功能解释如下:
The features of Cypress Dashboard are explained below −
-
It provides data on the total number of passed, failed and skipped test cases.
-
The stack trace and screenshots of the failed tests are available.
-
The video of test execution is available.
-
Management of test data, framework and their access is possible.
-
The usage trends in the organization is provided.
Setup Cypress Dashboard
要设置流程,首先,我们应该转到Cypress Test Runner窗口中的Runs选项卡。然后单击Connect to Dashboard。将出现以下屏幕:
To set up the process, first, we should go to the Runs tab in the Cypress Test Runner window. Then, click on Connect to Dashboard. The following screen will appear −
我们将获得各种登录仪表板的选项,如下所示:
We shall get various options of logging on to the Dashboard, as shown below −
成功登录后,我们将收到成功消息。单击Continue。
After successful sign in, we shall get the success message. Click on Continue.
输入项目名称、所有者和可以看到该项目的用户。
Enter the project name, owner and users, who can see the project.
然后,单击Set up project。
Then, click on Set up project.
Cypress将给出以下建议:
Cypress shall then give the following suggestions −
-
project Id
-
unique project key (in form of command to be executed in terminal)
从 Cypress 建议获取的 projectId 应与项目文件夹中的 cypress.json 文件中可用的项目 ID 匹配。
The projectId obtained from the Cypress suggestion should match with the project id available in the cypress.json file within the project folder.
接下来,我们必须按 Cypress 建议运行下面提到的命令 -
Next, we have to run the below mentioned command as suggested by Cypress −
node_modules/cypress/bin/cypress run --record --key <project key>
下面给出的屏幕将会出现 -
The screen given below will appear −
执行完成后,我们必须打开测试运行器的运行选项卡。它包含有关平台、浏览器和测试持续时间的信息。
Once the execution is done, we have to open the Runs tab of the Test Runner. It has the information on platform, browser, and duration of the tests.
测试记录应该可见。单击记录。
The test records shall be visible. Click on a record.
记录在浏览器中打开,其中带有测试结果概述(已通过、失败、待处理、跳过的数量),如下所示。
The record is opened in a browser, with the test result Overview (count of passed, failed, pending, skipped), as shown below.
在 Specs 选项卡中,我们应该有每项测试及其结果的详细信息。
In the Specs tab, we should have the details of each test and its result.
此外,还有输出、失败的测试截图、视频等功能。
Additionally, there are features like output, failed test screenshot, videos, and so on.
Cypress - Screenshots and Videos
Cypress 可以处理屏幕截图和视频。首先,让我们了解 Cypress 如何帮助捕获屏幕截图。
Cypress can work on screenshots and videos. First, let us understand how Cypress can help in capturing the screenshot.
Screenshots
我们可以在 Cypress 中使用 screenshot 命令捕获整个页面和特定元素屏幕截图。
We can capture both the complete page and particular element screenshot with the screenshot command in Cypress.
此外,Cypress 还具有捕获失败测试屏幕截图的内置功能。要捕获特定场景的屏幕截图,我们使用命令 screenshot。
In addition to that Cypress has the in-built feature to capture the screenshots of failed tests. To capture a screenshot of a particular scenario, we use the command screenshot.
Screenshot Implementation
在 Cypress 中实现屏幕截图命令的方式如下 −
The implementation of the screenshot commands in Cypress is as follows −
describe('Tutorialspoint Test', function () {
// test case
it("Scenario 1", function () {
//URL launched
cy.visit("https://the-internet.herokuapp.com/javascript_alerts")
//complete page screenshot with filename - CompletePage
cy.screenshot('CompletePage')
//screenshot of particular element
cy.get(':nth-child(2) > button').screenshot()
});
});
Execution Results
Execution Results
输出如下 −
The output is given below −
执行日志显示完整页面屏幕截图已捕获(文件名是 CompletePage.png),以及特定元素(“单击 JS 确认”)的屏幕截图。
The execution logs show that complete full page screenshot captured (with filename as CompletePage.png) and also screenshot a particular element (Click for JS Confirm).
这些屏幕截图在项目中 screenshots 文件夹(在 plugins 文件夹中)内部捕获。可以通过更改全局配置,修改捕获屏幕截图的位置。
These screenshots got captured inside the screenshots folder (in the plugins folder) within the project. The location where the screenshots got captured, can be modified by changing the Global configurations.
为全页图像创建的 CompletePage.png 文件。
CompletePage.png file created for full page image.
按钮“单击 JS 确认”的屏幕截图已捕获。
The screenshot of the button Click for JS Confirm got captured.
在“测试运行器设置”选项卡中,参数 screenshotOnRunFailure 默认设置为 true 值。因此,总是为失败测试捕获屏幕截图。
In the Test Runner Settings tab, the parameter screenshotOnRunFailure, set to true value by default. Due to which, the screenshots are always captured for failure tests.
此外,screenshotsFolder 参数的值是 cypress/screenshots 值。因此,屏幕截图捕获在 screenshots 文件夹内部。
Also, the screenshotsFolder parameter has the value cypress/screenshots value. So, the screenshots are captured within the screenshots folder.
要禁用捕获失败屏幕截图的功能,我们必须在 cypress.json 文件中添加以下值 −
To disable feature of capturing failed screenshots, we have to add the below values in the cypress.json file −
Cypress.Screenshot.defaults({
screenshotOnRunFailure: false
})
Videos
默认情况下,Cypress 的视频录制功能对测试启用。它们存储在项目中的 videos 文件夹中。
The video capturing of Cypress is turned on for tests, by default. They are stored in the videos folder within the project.
一旦使用以下提到的命令运行 Cypress 测试 −
Once a Cypress test is run with the below mentioned command −
node_modules/.bin/cypress run
我们得到控制台消息以及视频位置、压缩详细信息等 −
We get the console message along with the location of the video, compression details, and so on −
我们在项目中同一位置获取相应的视频。
We get the corresponding video in the same location within the project.
要禁用视频捕获功能,我们必须在 cypress.json 文件中添加以下值 −
To disable the video capture feature, we have to add the below value in the cypress.json file −
{
"video": false
}
Cypress - Debugging
Cypress 具有非常好的调试功能,我们可以通过它进行时间旅行,并查看测试执行期间实际发生了什么。这可以通过将鼠标悬停在测试运行器日志上完成。
Cypress has a very good debugging feature, where we can time travel and see what has actually happened during the test execution. This can be done by hovering the mouse over the Test Runner logs.
当我们在测试运行器窗口中浏览各个步骤时,元素会高亮显示。我们还可以使用 Cypress 命令 pause。这会暂停执行,在此期间我们可以调试前一个步骤。之后,我们可以再次恢复执行。
As we move through the steps in the Test Runner window, the elements get highlighted.We can also use the Cypress command pause. This pauses the execution, during which we can debug the previous steps. After that, we can again resume execution.
Implementation
用于在 Cypress 中调试的命令的实现如下 −
The implementation of commands for debugging in Cypress is as follows −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch the application
cy.visit("https://accounts.google.com");
// enable cookie logging
Cypress.Cookies.debug(true)
cy.getCookies
//pause execution
cy.pause()
cy.setCookie('cookie1', 'value1' )
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
输出日志显示执行已暂停(由已暂停按钮表示)。然后,我们可以在调试完前一个步骤后再次恢复执行,方法是单击恢复按钮(显示在已暂停按钮旁边)。
The output logs show that the execution has been paused (denoted by Paused button).Then again, we can resume it after debugging the previous steps by clicking the Resume button (appear beside Paused button).
输出日志现在包含从暂停恢复后执行的所有步骤。
The output logs now have all the steps executed after resume from pause.
如果我们在浏览器中打开开发者控制台(按 F12),并从测试运行器中选择一个步骤,控制台将显示所用命令和产生值。
If we open the Developer Console (pressing F12) on the browser, and select a step from the Test Runner, the Console shall show the Command used and the valued Yielded.
例如,对于 setCookie 步骤,控制台显示命令 − setCookie,而产生值显示 cookie 名称 − cookie1 和值 − value1。
For example, for the setCookie step, the Console shows Command − setCookie and Yielded shows the cookie name − cookie1 and value − value1.
Cypress - Custom Commands
Cypress 自定义命令由用户描述,而不是 Cypress 中的默认命令。这些自定义命令用于创建在自动化流程中重复的测试步骤。
Cypress custom commands are described by users and not the default commands from Cypress. These customized commands are used to create the test steps that are repeated in an automation flow.
我们可以添加覆盖已存在的命令。它们应放置在 Cypress 项目中 support 文件夹内的 commands.js 文件中。
We can add and overwrite an already pre-existing command. They should be placed in the commands.js file within the support folder present in the Cypress project.
Syntax
Cypress 中自定义命令的语法如下 −
The syntax for the custom commands in Cypress is as follows −
Cypress.Commands.add(function-name, func)
Cypress.Commands.add(function-name, opts, func)
Cypress.Commands.overwrite(function-name, func)
在此,
Here,
-
function-name is the command that is being added/overwritten.
-
func is the function passing that gets arguments passed to command.
-
opts is used to pass an option to describe the implicit characteristics of custom command. It is also used to determine how to handle a prior yielded subject (only applicable to Cypress.Commands.add()) and default value of option is false. The option prevSubject accepts false to ignore prior subjects, accepts true to accept prior subject and accepts optional to either begin a chain or utilize a pre-existing chain. An option accepts string, array, or Boolean.
Implementation of custom command
下面给出了 commands.js 中自定义命令的实现
Given below is the implementation of custom command in commands.js
Cypress.Commands.add("userInput", (searchTxt) => {
//to input search text in Google and perform search
cy.get("input[type='text']").type(searchTxt);
cy.contains("Google Search").click();
});
Implementation of Actual Test
下面给出了使用自定义命令在 Cypress 中实现实际测试的情况 −
Given below is the implementation of actual test in Cypress with custom command −
describe('Tutorialspoint Test', function () {
// test case
it('Test Case 6', function (){
// launch the application
cy.visit("https://www.google.com/");
//custom parent command
cy.userInput('Java')
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
输出日志显示自定义命令 – userInput (具有 get、type 和 click 命令)正在执行。
The output logs show the custom command – userInput (having get, type and click commands) getting executed.
建议自定义命令不要太长。它应该简短,因为在自定义命令中添加太多操作往往会显示执行。
It is recommended that a custom command should not be too lengthy. It should be brief,because, adding too many actions within a custom command tends to show the execution.
Cypress - Fixtures
利用 Cypress 的装置来维护并保存自动化的测试数据。 装置保存在 Cypress 项目中的装置文件夹(example.json 文件)中。基本上,它帮助我们从外部文件读取数据输入。
Cypress fixtures are added to maintain and hold the test data for automation. The fixtures are kept inside the fixtures folder (example.json file) in the Cypress project. Basically, it helps us to get the data input from external files.
Cypress 装置文件夹可以具有 JSON 或其他格式的文件,数据保存在“键:值”对中。
Cypress fixtures folder can have files in JSON or other formats and the data is maintained in "key:value" pairs.
所有测试数据都可以被多个测试使用。所有固定数据都必须在 before 钩子块内声明。
All the test data can be utilised by more than one test. All fixture data has to be declared within the before hook block.
Syntax
Cypress 数据驱动的测试语法如下所示:
The syntax for Cypress data driven testing is as follows −
cy.fixture(path of test data)
cy.fixture(path of test data, encoding type)
cy.fixture(path of test data, opts)
cy.fixture(path of test data, encoding type, options)
在此,
Here,
-
path of test data is the path of test data file within fixtures folder.
-
encoding type − Encoding type (utf-8, asci, and so on) is used to read the file.
-
Opts − Modifies the timeout for response. The default value is 30000ms. The wait time for cy.fixture(), prior throws an exception.
Implementation in example.json
以下是 example.json 在 Cypress 中使用数据驱动测试的实现 −
Given below is the implementation of data driven testing with example.json in Cypress −
{
"fullName": "Robert",
"number": "789456123"
}
Implementation of Actual Test
在 Cypress 中实际进行数据驱动测试的实现如下:
The implementation of actual data driven testing in Cypress is as follows −
describe('Tutorialspoint Test', function () {
//part of before hook
before(function(){
//access fixture data
cy.fixture('example').then(function(regdata){
this.regdata=regdata
})
})
// test case
it('Test Case1', function (){
// launch URL
cy.visit("https://register.rediff.com/register/register.php")
//data driven from fixture
cy.get(':nth-child(3) > [width="185"] > input')
.type(this.regdata.fullName)
cy.get('#mobno').type(this.regdata.number)
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
输出日志显示值 Robert 和 789456123 分别被输入到姓名和手机号码字段。此数据已从装置传递到测试。
The output logs show the values Robert and 789456123 being fed to the Full Name and Mobile No. fields respectively. This data has been passed to the test from the fixtures.
Cypress - Environment Variables
我们可以定义环境变量,为测试自动化框架全局声明,并且所有测试用例都可以访问它。这种类型的自定义环境变量可以存储在我们项目内的 cypress.json 文件中。
We can define environment variables that can be globally declared for the test automation framework and all the test cases can access it. This type of customized environment variable can be stored in the cypress.json file within our project.
由于 Cypress 的默认配置未公开自定义变量,因此我们必须在 cypress.json 文件中提及键值“evn”,然后设置其值。
Since, a customized variable is not exposed by default configurations from Cypress, we have to mention the key as "evn" in the cypress.json file and then, set the value.
另外,为了在实际测试中访问该变量,我们必须使用 Cypress.env 并传递在 json 文件中声明的值。
Also, to access this variable in the actual test, we have to use the Cypress.env and pass the value declared in the json file.
Implementation in cypress.json
以下是 cypress.json 格式中环境变量命令的实现−
The implementation of commands for environment variables in cypress.json format is as follows −
{
"projectId": "fvbpxy",
"env" :
{
"url" : "https://www.google.com/"
}
}
Implementation of Actual Test
以下是 Cypress 中环境变量的实际测试的实现 −
The implementation of actual test for environmental variables in Cypress is as follows −
describe('Tutorialspoint Test', function () {
// test case
it('Scenario 1', function (){
// launch application from environment variable
cy.visit(Cypress.env('url'))
cy.getCookies()
cy.setCookie('cookie1', 'value1')
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
输出日志显示了作为 cypress.json 文件中的自定义环境变量设置的发起 URL。
The output logs show the URL launched which has been set as a customized environment variable from the cypress.json file.
Configure Environment Variables
我们可以通过 --env 标志从命令行配置或修改环境值。
We can configure or modify the environment values from the command line with the flag --env.
要以有头模式运行特定文件(例如:Test1.js),同时其网址为: https://accounts.google.com ,命令如下:
To run a particular file (for example: Test1.js) with URL: https://accounts.google.com in a headed mode, the command shall be as follows:
./node_modules/.bin/cypress run --spec cypress/integration/examples/Test1.js --
env url=https://accounts.google.com –headed
如果我们在 cypress.json 文件中为环境变量网址设置了某一值,与从命令行设置的值不同,Cypress 将优先使用从命令行设置的值。
If we have a value set for the environment variable url in the cypress.json file, which is different from the value set from the command line, Cypress shall give preference to the value set from the command line.
Cypress - Hooks
Cypress Hooks 用于在每次测试之前/之后执行某些操作。一些常见的 hooks 如下:
Cypress Hooks are used to carry out the certain operations prior/post every/each test.Some of the common hooks are as follows −
-
before − It is executed, once the prior execution of any tests within a describe block is carried out.
-
after − It is executed, once the post execution of all the tests within a describe block is carried out.
-
beforeEach − It is executed prior to the execution of an individual, it blocks within a describe block.
-
afterEach − It is executed post execution of the individual, it blocks within a describe block.
Implementation
下面对 Cypress Hooks 命令的实现进行了说明:
The implementation of commands for the Cypress Hooks is explained below −
describe('Tutorialspoint', function() {
before(function() {
// executes once prior all tests in it block
cy.log("Before hook")
})
after(function() {
// executes once post all tests in it block
cy.log("After hook")
})
beforeEach(function() {
// executes prior each test within it block
cy.log("BeforeEach hook")
})
afterEach(function() {
// executes post each test within it block
cy.log("AfterEac hook")
})
it('First Test', function() {
cy.log("First Test")
})
it('Second Test', function() {
cy.log("Second Test")
})
})
Execution Results
Execution Results
输出如下:
The output is mentioned below −
输出日志显示,首先执行的步骤是 BEFORE ALL。
The output logs show that the first executed step is the BEFORE ALL.
最后一个执行的步骤是 AFTER ALL。两者都只运行一次。
The last executed step is the AFTER ALL. Both of them ran only once.
在每个 BEFORE EACH 下执行的步骤运行两次(在每个 TEST BODY 之前)。
The step executed under BEFORE EACH ran twice (before each TEST BODY).
而且,在每个 AFTER EACH 下执行的步骤运行两次(在每个 TEST BODY 之后)。
Also, step executed under AFTER EACH ran twice (after each TEST BODY).
这两个 it 块按实现的顺序执行。
Both the it blocks are executed in order, in which they are implemented.
TAG
除了钩子,Cypress 还有标签 - .only 和 .skip。
Apart from hooks, Cypress has tags - .only and .skip.
而 .only 标签用于执行它所标记的 it 块,.skip 标签则用于排除它所标记的 it 块。
While the .only tag is utilised to execute the it block to which it is tagged, the .skip tag is utilised to exclude the it block to which it is tagged.
Implementation with .only
The implementation of .only tag in Cypress is as follows −
describe('Tutorialspoint', function()
//it block with tag .only
it.only('First Test', function() {
cy.log("First Test")
})
//it block with tag .only
It.only('Second Test', function() {
cy.log("Second Test")
})
it('Third Test', function() {
cy.log("Third Test")
})
})
Execution Results
Execution Results
输出如下 −
The output is given below −
输出日志显示带有 .only 标签的 it 块(第一个和第二个测试)只得到了执行。
The output logs show that the it blocks (First and Second Test) with the .only tags only got executed.
Implementation with .skip
The implementation of .skip tag in Cypress is as follows −
describe('Tutorialspoint', function()
it('First Test', function() {
cy.log("First Test")
})
it('Second Test', function() {
cy.log("Second Test")
})
//it block with tag .skip
it.skip('Third Test', function() {
cy.log("Third Test")
})
})
Execution Results
Execution Results
输出如下 −
The output is as follows −
输出日志显示带有 .skip 标签的 it 块(第三个测试)跳过了执行。
The output logs show that the it block (Third Test) with the .skip tag got skipped from the execution.
Cypress - Configuration of JSON File
Cypress 配置由一些适用于框架内所有测试的键值对组成。Cypress 默认配置可在测试运行器窗口中的“设置”选项卡→“配置”(展开它)下找到。
Cypress configurations consist of some key-value pairs that are applicable to all tests within a framework. Cypress default configurations are available under the Settings tab→Configuration (expand it) in the Test Runner window.
如果我们在同一窗口中向下看,我们应该看到 Cypress 给出的多个配置的现有值,例如超时、环境变量、文件夹路径等。
If we look further down in the same window, we shall have the existing values of multiple configurations given by Cypress like the timeouts, environment variables, folder path, and so on.
它如下所示:
It is displayed below −
如果我们在同一窗口中向下看,我们应该看到 Cypress 给出的多个配置的现有值,例如超时、环境变量、文件夹路径等。
If we look further down in the same window, we shall have the existing values of multiple configurations given by Cypress like the timeouts, environment variables, folder path, and so on.
它如下所示:
It is displayed below −
Override Default values
要从 cypress.json 文件覆盖默认配置,我们必须指定键值对。
To override the default configurations from the cypress.json file, we have to specify the key-value pairs.
Implementation in cypress.json
覆盖 JSON 文件的默认值实现如下:
The implementation for overriding the default values for JSON file is as follows −
{
"baseUrl" : "https://www.google.com/"
}
此处,键是 baseUrl,值是 https://www.google.com/ 。一旦再次运行测试,就会 changes are reflected in the global configurations ,如下所示:
Here, the key is baseUrl and the value is https://www.google.com/. Once the tests are run again, the changes are reflected in the global configurations, as shown below −
Implementation of Actual Test
覆盖 JSON 文件的默认值的实际测试实现如下:
The implementation of actual test for overriding default values of the JSON file is as follows −
describe('Tutorialspoint', function () {
// test case
it('First Test', function (){
// launch application from configuration
cy.visit("/")
});
});
Execution Results
Execution Results
输出如下 −
The output is as follows −
执行日志显示 baseUrl 已从 cypress.json 文件获取,并且适用于框架内的所有测试。
The execution logs show that the baseUrl has been obtained from the cypress.json file and it is applicable to all tests within the framework.
Override Default configurations
我们可以从测试脚本覆盖默认配置,这将适用于测试用例内的单个测试步骤,而不仅适用于完整框架。
We can override the default configurations from the test scripts, which become applicable to an individual test step, within the test case and not to the complete framework.
这是在 Cypress 中借助 config 命令完成的。
This is done with the help of the config command in Cypress.
例如,如果我们希望为特定测试步骤增加默认超时,实现如下所示:
For example, if we want to increase the default timeout for a particular test step, implementation shall be as follows −
//set default time out to nine seconds from following steps in test
Cypress.config('defaultCommandTimeout',9000)
landPage.selectUser().click()
同时,如果在 cypress.json 文件中将 defaultCommandTimeout 值设置为 7 秒,那么 Cypress 将优先考虑应用于测试步骤的超时(即 9 秒)。
Simultaneously if the defaultCommandTimeout value is set to seven seconds in the cypress.json file, then Cypress shall give preference to the timeout applied to the test step(i.e nine seconds).
最后,它优先考虑默认配置。
Finally, it gives preference to the default configurations.
Disable Overriding Default configurations
我们可以禁用从 cypress.json 中覆盖默认配置的功能。
We can disable the feature to override the default configurations from the cypress.json.
cypress.json 中的配置如下:
The configuration in cypress.json is as follows −
{
"defaultCommandTimeout" : "9000"
}
要禁用以上配置,运行以下命令:
To disable the above configuration, run the below mentioned command −
npx cypress open --config-file false
在运行上述命令后,测试运行器窗口的设置选项卡将显示 config 标记设置为 false。
After running the above command, the Settings tab of the Test Runner window will show the config flag set to false.
此外,defaultCommandTimeout 被设为 4 秒,这是由默认配置设定的,并且不会被 cypress.json 的 9 秒值覆盖。
Also, defaultCommandTimeout is set to four seconds, which is set by the default configuration and not overridden by cypress.json value of nine seconds.
Cypress - Reports
Cypress 与 Mocha 捆绑在一起。因此,任何可为 Mocha 生成的报告也可用于 Cypress。此外,Cypress 还有其他第三方报告工具,如 JUnit 和 teamcity。
Cypress is bundled with Mocha. So, any reports that can be generated for Mocha, can also be utilised with Cypress. In addition to that Cypress has other third party reporters like JUnit and teamcity.
Mochawesome Report
Mochawesome 报告是 Cypress 中最重要的报告之一。
The Mochawesome report is one of the most important reports in Cypress.
-
To install mochawesome, run the command given herewith −
npm install mochawesome --save-dev
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
-
To install mocha, run the command mentioned below −
npm install mocha --save-dev
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
-
To merge mochawesome json reports, run the following command −
npm install mochawesome-merge --save-dev
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
安装后,所有这些包都应该反映在 package.json 文件中。
All these packages after installation, should get reflected on the package.json file.
要将多个报告合并为一个报告,运行以下命令:
To merge multiple reports in a single report, run the following command −
npm run combine-reports
Configurations in cypress.json file
在 cypress.json 文件中,我们可以为 mochawesome 报告设置以下配置:
In the cypress.json file, we can set the following configurations for the mochawesome reports −
-
overwrite − If its value is set to false, there should not be any overwriting from the prior generated reports.
-
reportDir − It is the location, where reports are to be saved.
-
quiet − If its value is set to true, there should not be any Cypress related output. Only the mochawesome output has to be printed.
-
html − If its value is set to false, there should not be any generation of html reports after execution.
-
json − If its value is set to true, a json file with execution details will be generated.
Implementation in cypress.json
在 cypress.json 中对 mochawesome 报告的实现如下:
The implementation for mochawesome report in cypress.json is as follows −
{
"reporter": "mochawesome",
"reporterOptions": {
"reportDir": "cypress/results",
"overwrite": false,
"html": false,
"json": true
}
}
要为 Cypress 项目的 integration 文件夹中的所有规范生成报告,请运行下面给出的命令:
To generate a report for all specs in the integration folder of the Cypress project, run the command given below −
npx cypress run
要运行特定测试,请运行以下命令:
For running a particular test, run the following command −
npx cypress run --spec "<path of spec file>"
执行完成后,会在 Cypress 项目中生成 mochawesome-report 文件夹,其中包含 html 和 json 格式的报告。
After the execution is completed, the mochawesome-report folder gets generated within the Cypress project containing reports in html and json formats.
右键单击 mochawesome.html 报告。然后,选择复制路径选项,并在浏览器上打开复制的路径。
Right-click on the mochawesome.html report. Then, select the Copy Path option and open the path copied on the browser.
mochawsome 报告将以执行结果、持续时间、测试用例名称、测试步骤等的详细信息的形式打开。
The mochawesome report gets opened with details of the execution results, duration, test case name, test steps, and so on.
单击屏幕左上角的图标(在上图中突出显示),将显示更多选项。
On clicking on the icon (highlighted in the above image) on the left upper corner of the screen, more options are displayed.
我们可以获得不同的视图来选择通过、失败、挂起、跳过的测试用例以及应用于测试的钩子。
We can get the different views to select the passed, failed, pending, skipped test cases, and the hooks applied to the test.
JUnit Report
Cypress 提供了另一种称为 JUnit 报告的报告类型。
Cypress provides one more type of report known as the JUnit report.
要为 JUnit 报告安装程序包,请运行下面说明的命令:
To install the package for JUnit report, run the command stated below −
npm install cypress-junit-reporter --save-dev
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
Implementation in cypress.json
下面是对 cypress.json 中 JUnit 报告的实现:
Given below is an implementation of JUnit report in cypress.json −
{
"reporter": "junit",
"reporterOptions": {
"mochaFile": "cypress/results/results.xml",
"toConsole": true
}
}
如果我们在某个运行中运行多个测试,并且希望单独的规范文件有唯一的报告,我们必须在cypress.json中mochaFile参数中添加[hash]。
If we run multiple tests in a run, and wish to have a unique report for the individual spec files, we have to add [hash] in the mochaFile parameter in cypress.json.
Implementation to avoid overriding report
以下是cypress.json中的一个实现,以避免Cypress中有优先报告
Following is an implementation in cypress.json to avoid an overriding report in Cypress −
{
"reporter": "junit",
"reporterOptions": {
"mochaFile": "cypress/results/results-[hash].xml",
"toConsole": true
}
}
要生成Cypress项目中integration文件夹中所有规格的报告,请运行以下命令:
To generate report for all specs in the integration folder of the Cypress project, run the following command −
npx cypress run --reporter junit
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
执行完成后,Cypress项目中会生成一个results文件夹,其中包含xml格式的报告。
After execution is completed, the results folder gets generated within the Cypress project containing reports in xml format.
teamcity Report
Cypress提供了一种被称为TeamCity的报告的另一种报告类型。
Cypress provides one more type of report known as the teamcity report.
要安装teamcity报告的软件包,请运行以下命令:
To install the package for teamcity report, run the following command −
npm install cypress-teamcity-reporter --save-dev
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
要生成Cypress项目中integration文件夹中所有规格的报告,请运行以下命令:
To generate report for all specs in the integration folder of the Cypress project, run the following command −
npx cypress run --reporter teamcity
以下屏幕将出现在您的计算机上:
The following screen will appear on your computer −
Cypress - Plugins
Cypress 有多个插件可添加到其功能中。有多种类型的插件,例如身份验证、组件测试、自定义命令、开发工具等。
Cypress has multiple plugins to add to its features. There are multiple types of plugins like the authentication, component testing, custom commands, development tools and so on.
一些非常重要的插件包括 −
Some of the prominent plugins include −
要在 Cypress 中使用 perform file upload task ,我们必须首先使用下面提到的命令安装 install a plugin −
To perform file upload task in Cypress, we have to first install a plugin with the command mentioned below −
npm install –dev cypress-file-upload
安装完成后,我们必须在 command.js 文件中添加语句 import 'cypress-file-upload',该文件位于 Cypress 项目中的 support 文件夹内。
Once the installation is done, we have to add the statement import 'cypress-file-upload' in the command.js file, which resides inside the support folder within the Cypress project.
要使用框架,首先,我们必须使用下面给出的命令安装 Cypress plugin for frames −
To work with frames, first, we have to install the Cypress plugin for frames with the command given below −
npm install –D cypress-iframe
然后,我们必须在代码中添加语句 import 'cypress-iframe'。
Then, we have to add the statement import 'cypress-iframe' in the code.
要 identify elements with xpath locator ,运行以下命令 −
To identify elements with xpath locator, run the following command −
npm install cypress-xpath
安装完成后,我们必须在 index.js 文件中添加语句 require (“cypress-xpath”),该文件位于 Cypress 项目中的 support 文件夹内。
Once the installation is done, we have to add the statement require ("cypress-xpath") within the index.js file, which resides inside the support folder within the Cypress project.
此外,我们必须使用 cy.xpath 命令来识别元素。
Also, we have to use the cy.xpath command to identify elements.
要 enable themes ,我们必须使用下面提到的命令安装一个插件 −
To enable themes, we have to install a plugin with the command mentioned below −
npm install --save-dev cypress-dark
安装完成后,我们必须在 index.js 文件中添加语句 require ("cypress-dark”),该文件位于 Cypress 项目中的 support 文件夹内。
Once the installation is done, we have to add the statement require ("cypress-dark") within the index.js file, which resides inside the support folder within the Cypress project.
Cypress - GitHub
要将 Cypress 与 GitHub 集成,我们必须首先安装 Cypress GitHub App。这可以通过组织集成设置或 Cypress 仪表板中的项目设置完成。
To integrate Cypress with GitHub, we have to first install Cypress GitHub App. This can be done either from the organization integration settings or from the project settings in the Cypress Dashboard.
Installation
Cypress GitHub App 的安装可以通过两种方式完成。它们在下面详细解释。
The installation of Cypress GitHub App can be done in two ways. They are explained below in detail.
Installation via organization integration settings
按照以下步骤通过组织集成设置安装 GitHub -
Follow the steps mentioned below to install GitHub via organization integration settings −
-
Navigate to the Dashboard Organization page.
-
Choose an organization that you want to integrate with a GitHub account or organization.
-
Navigate to the chosen organization’s integration option from the navigation to the side.
-
Then, click the GitHub Integration button.
Installation via project settings
按照以下步骤通过项目设置安装 GitHub -
Follow the steps mentioned below to install GitHub via project settings −
-
Choose organization inside organization switcher.
-
Choose the project that you want to integrate with the repo in GitHub.
-
Move to the Project settings page.
-
Go to the GitHub Integration.
-
Click on Install the Cypress GitHub App.
完成 GitHub 应用安装后,我们将被重定向到 GitHub.com,以便继续执行以下步骤:
Once the GitHub App installation is done, we shall be directed to GitHub.com to proceed with further steps, which are as follows −
-
Choose the GitHub organization or account for integration with the organization Cypress Dashboard.
-
Next, we have to combine either all GitHub repositories or a particular repository with the Cypress GitHub App.
-
Click on the Install button to finish installation.
GitHub Integration Enabling
下面介绍了在 Cypress 中启用 GitHub 集成的流程:
The process to enable the GitHub integration in Cypress is explained below −
-
Move to the project settings page.
-
Navigate to the GitHub Integration section, then click on Configure.
-
Select a repository from GitHub to integrate with the project.
-
As GitHub repo is connected to a Cypress project, the GitHub integration shall be enabled.