Home > Software design >  Cypress with typescript custom commands type error
Cypress with typescript custom commands type error

Time:01-21

I've setup custom commands for my Cypress tests :

// cypress/support/commands.ts
/// <reference types="cypress"/>

Cypress.Commands.add('getByTestId', (target: [string], timeout: number = 0) => {
    target[0] = `[data-testid="${target[0]}"]`;
    return cy.get(target.join('>'), { timeout });
});



// cypress/support/index.ts
/// <reference types="cypress" />
declare global {
namespace Cypress {
    interface Chainable {
        getByTestId(id: string): Chainable<Element>;
    }
  }
}

these are my files where I setup my commands.

When writing test I have this error even if I had this on the top of my file /// <reference types="cypress" /> :

cypress/integration/filename.test.e2e.ts

sample.test.e2e.ts

CodePudding user response:

This worked for me :

// tsconfig.json

"include": [
    "cypress/support/*.ts"
]

CodePudding user response:

I also have Cypress TypeScript support and ran into some issues at the beginning. The following setup worked for me:

// cypress/plugins/index.ts
/// <reference types="cypress" />

// cypress/support/commands.ts
declare namespace Cypress {
  interface Chainable<Subject> {
    getByTestId(selector: string, ...options: any): Chainable<JQuery<HTMLElement>>;
  }
}

// cypress/support/commands.ts
Cypress.Commands.add('getByTestId', (selector, ...options) => {
  return cy.get(`[data-test=${selector}]`, ...options);
});

So I have the type reference in the plugins/index.ts file and the namespace declaration as well as custom command definitions in support/commands.ts. I am using the currently newest Cypress version 9.3.1.

Additionally, another thing I've also noticed is when you try to import stuff into commands.ts, you will also get the error you described.

  •  Tags:  
  • Related