Getting jsdoc and intellisense from custom cypress commands

Viewed 760

I am currently setting up cypress for my project, and thought it would be a good idea to create a bunch of commands to keep the tests more readable.

so I added this in support/commands.js

Cypress.Commands.add(
  "signup",
  ({ email, displayName, password, companyName, registrationKey, stub }) => {
    cy.visit("http://localhost:3000/signup").wait(1);
    if (stub) {
      cy.intercept("POST", "/signup.json", stub);
    }
    cy.get("#email-address").type(email);
    cy.get("#displayName").type(displayName);
    if (companyName) cy.get("#companyName").type(companyName);
    cy.get("#password").type(password);
    cy.get("#repeat-password").type(password);
    cy.get("button").click().wait(1);
    cy.get("#error-message").should("not.exist");
  }
);

and I can use it in my specs and it does what it should. However I am not getting any sort of intellisense on the command when writing my tests.

ex

/// <reference types="cypress" />
describe("test", () => {
  it("can signup", () => {
    cy.signup({
      email: "mail@mail.com",
      displayName: "cool_dude",
      password: "Password1",
      companyName: "Not a scam AB",
    });
  });
});

And I have to refer to the commands.js file to see what options I have for the signup function.

So I am wondering if it is possible to add jsdoc to custom cypress commands, and if so, how?

2 Answers

If you're using VSCode, try using the Cypress Helper extension. It will handle some of this for you. After installing it, go into the extension settings, scroll to the botton, and you'll see the Type Definition On Save setting. Check that box, and it will generate the *.d.ts file entries based on your custom commands, every time you save.

After that, creating Intellisense text is as easy as writing JSDoc comments above your custom command, like so:

/**
 * Logs in the user
 */
Cypress.Commands.add('logIn', (email) => {
  doSomeLoginStuff()
})

Saving this results in the following code being added to a d.ts file in the same folder:

/**
 * Logs in the user
 */
logIn(email: any): Chainable<any>

Probably the simplest way to do it is to follow the official guide Types for Custom Commands. It's not JSDoc solution but it works.

// cypress/support/index.ts
Cypress.Commands.add('dataCy', (value) => {
  return cy.get(`[data-cy=${value}]`)
})


// in cypress/support/index.ts
// load type definitions that come with Cypress module
/// <reference types="cypress" />
declare global {
  namespace Cypress {
    interface Chainable {
      /**
       * Custom command to select DOM element by data-cy attribute.
       * @example cy.dataCy('greeting')
       */
      dataCy(value: string): Chainable<Element>
    }
  }
}
Related