Cypress 简明教程
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.