1

Appologies for the huge photos, I dont know how to make them smaller.

I guess I'll dive straight in to my issue. I have the following folder structure:

enter image description here

I am trying to create a repo of custom cypress commands. I have run into 2 issues.

Firstly if I rename the commands.ts to index.ts I get a bunch of weird typing issues(even if Chainable is returning void). enter image description here

this is the index.d.ts(Chainable here but same issue with returning void):

If I rename the index.ts to commands.ts again and try to build it I get the following issue:

enter image description here

So quite a few issues here. Id appreciate if someone can guide me through this process.

Fody
  • 23,754
  • 3
  • 20
  • 37

1 Answers1

0

The following works for me, which I believe is the "standard" way to add custom commands in typescript.

cypress/support/commands.ts

/// <reference types="cypress" />

declare namespace Cypress {
  interface Chainable<Subject = any> {
    /**
     * Custom command to select DOM element by data-test-id attribute.
     * @example cy.getDataTestId('greeting')
     */
     getDataTestId(value: string): Chainable<JQuery<Element>>
  }
}

Cypress.Commands.add('getDataTestId', (value: string) => {
  return cy.get(`[data-test-id="${value}"]`)
})

Notes on changes

  • everything is in command.ts including the type definition (ref Types for custom commands)

  • there is an cypress/support/index.ts that imports cypress/support/commands.ts

  • return type is Chainable<JQuery<Element>>

  • the custom command is not assigned to a variable


Typescript ref Including declarations in your npm package

If your package has a main .js file, you will need to indicate the main declaration file in your package.json file as well. Set the types property to point to your bundled declaration file. For example:

  {
    "name": "awesome",
    "author": "Vandelay Industries",
    "version": "1.0.0",
    "main": "./lib/main.js",           // NOTE .js extension
    "types": "./lib/main.d.ts"
  }
Fody
  • 23,754
  • 3
  • 20
  • 37
  • I dont have any problem setting up custom commands with Cypress. Im just not sure on the NPM module part, do you need an index.ts file? etc I was trying to follow this guide: https://glebbahmutov.com/blog/publishing-cypress-command/ – rogue_particle Mar 13 '22 at 23:31
  • You can name the file anything you want, to publish you need a "main" entry in package.json. If your file is `src/index.ts` then `"main": "src"` as per Gleb's example. You need to `tsc --build` before publishing which creates `index.js` in the same folder, and that's the entry point in the client app (where you install cy-custom-commands package). – Fody Mar 14 '22 at 00:45