使用custom commands可以创建自定义命令和替换现有命令。
    自定义命令默认存放在cypress/support/commands.js文件中,它会在任何测试文件被导入之前加载,(定义在cypress/support/index.js中)。

    1. //index.js
    2. // ***********************************************************
    3. // This example support/index.js is processed and
    4. // loaded automatically before your test files.
    5. //
    6. // This is a great place to put global configuration and
    7. // behavior that modifies Cypress.
    8. //
    9. // You can change the location of this file or turn off
    10. // automatically serving support files with the
    11. // 'supportFile' configuration option.
    12. //
    13. // You can read more here:
    14. // https://on.cypress.io/configuration
    15. // ***********************************************************
    16. // Import commands.js using ES2015 syntax:
    17. import './commands'
    18. // Alternatively you can use CommonJS syntax:
    19. // require('./commands')
    20. // beforeEach(function(){
    21. // cy.log(`当前测试系统环境变量为${JSON.stringify(Cypress.config())}`)
    22. // })

    自定义命令语法如下:

    1. Cypress.Commands.add(name, callbackFn)
    2. Cypress.Commands.add(name, options, callbackFn)
    3. Cypress.Commands.overwrite(name, callbackFn)

    其中:name表示自定义命令的名称,callbackFn表示自定义命令的回调函数,回调函数里定义了自定义函数所需完成的操作步骤。
    options允许定义自定义命令的隐形行为。

    参数 可选值 默认值
    prevSubject true、false、optional false

    实例:kitten登陆

    1. // commands.js
    2. ///<reference types='cypress' />
    3. // kitten 登陆
    4. Cypress.Commands.add('loginRequest', (user, pwd) =>{
    5. return cy.request({
    6. method: 'POST',
    7. url: Cypress.env(Cypress.env('testEnv'))['CODEMAO_HOST']+'/tiger/v3/web/accounts/login',
    8. form: false,
    9. failOnStatusCode:true,
    10. body: {
    11. "identity": user,
    12. "password": pwd,
    13. "pid": "OqMVXvXp"
    14. },
    15. }).then((res) =>{
    16. cy.log(res.status);
    17. cy.log(res.statusText);
    18. expect(res.body['user_info']).property('id').to.be.a('number');
    19. });
    20. });
    1. // testLogin.js
    2. ///<reference types='cypress' />
    3. import LoginPage from '../../pages/login.page'
    4. describe('kitten登陆测试', function(){
    5. var username = Cypress.env(Cypress.env('testEnv'))['USERNAME'];
    6. const password = Cypress.env(Cypress.env('testEnv'))['PASSWORD'];
    7. beforeEach(function(){
    8. cy.loginRequest(username, password); //用例集开始执行之前调用自定义命令,即每个用例执行之前就已经是登陆状态
    9. });
    10. it('测试登陆成功', function(){
    11. const logininstance = new LoginPage()
    12. logininstance.isTargetPage();
    13. cy.url().should('include', Cypress.env(Cypress.env("testEnv"))['URL'])
    14. });
    15. });