'Issues with setting up cypress custom command npm module

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.



Solution 1:[1]

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"
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1