首页 > 解决方案 > Cypress new command definition reference

问题描述

i created custom commands in Cypress, and then used them in my test.spec.js but when i try to go to the definition of my command (ctrl + rightClick) it shows (Any) and no reference. is there any solution for that ? because if someone else try to read my test script it will not be easy to know where the commad definition is ...

test.spec.js

    describe('test', () => {
      before('Login before', () => {
        cy.visit('/');
        // my custom command cy.login()
         cy.login();
      });
    });

commands.js

    // definition of the command 
    Cypress.Commands.add('login', () => {
      // body of the command 
    });

标签: javascriptreferencecommandcypressdefinition

解决方案


Yes, there is a way.

You add one TS file in support/.

support/commands.d.ts:

declare namespace Cypress {
  interface Chainable<Subject> {    

    /**
     * Logs in a user
     *
     * @param {string} name User to log in
     * @example
     *    cy.login('admin');
     *
     */
    login(name: string): Chainable<any>
  }
}

The command will be added into cy object, so when I type it will suggest the new custom command as well:

enter image description here

You can see there's info about the command when you hover over it:

enter image description here

Plus you will be takes to commands.d.ts file when you click on it with Ctrl pressed.


推荐阅读