使用custom commands可以创建自定义命令和替换现有命令。
自定义命令默认存放在cypress/support/commands.js文件中,它会在任何测试文件被导入之前加载,(定义在cypress/support/index.js中)。
//index.js// ***********************************************************// This example support/index.js is processed and// loaded automatically before your test files.//// This is a great place to put global configuration and// behavior that modifies Cypress.//// You can change the location of this file or turn off// automatically serving support files with the// 'supportFile' configuration option.//// You can read more here:// https://on.cypress.io/configuration// ***********************************************************// Import commands.js using ES2015 syntax:import './commands'// Alternatively you can use CommonJS syntax:// require('./commands')// beforeEach(function(){// cy.log(`当前测试系统环境变量为${JSON.stringify(Cypress.config())}`)// })
自定义命令语法如下:
Cypress.Commands.add(name, callbackFn)Cypress.Commands.add(name, options, callbackFn)Cypress.Commands.overwrite(name, callbackFn)
其中:name表示自定义命令的名称,callbackFn表示自定义命令的回调函数,回调函数里定义了自定义函数所需完成的操作步骤。
options允许定义自定义命令的隐形行为。
| 参数 | 可选值 | 默认值 |
|---|---|---|
| prevSubject | true、false、optional | false |
实例:kitten登陆
// commands.js///<reference types='cypress' />// kitten 登陆Cypress.Commands.add('loginRequest', (user, pwd) =>{return cy.request({method: 'POST',url: Cypress.env(Cypress.env('testEnv'))['CODEMAO_HOST']+'/tiger/v3/web/accounts/login',form: false,failOnStatusCode:true,body: {"identity": user,"password": pwd,"pid": "OqMVXvXp"},}).then((res) =>{cy.log(res.status);cy.log(res.statusText);expect(res.body['user_info']).property('id').to.be.a('number');});});
// testLogin.js///<reference types='cypress' />import LoginPage from '../../pages/login.page'describe('kitten登陆测试', function(){var username = Cypress.env(Cypress.env('testEnv'))['USERNAME'];const password = Cypress.env(Cypress.env('testEnv'))['PASSWORD'];beforeEach(function(){cy.loginRequest(username, password); //用例集开始执行之前调用自定义命令,即每个用例执行之前就已经是登陆状态});it('测试登陆成功', function(){const logininstance = new LoginPage()logininstance.isTargetPage();cy.url().should('include', Cypress.env(Cypress.env("testEnv"))['URL'])});});
