Cypress Custom TypeScript Command is not a Function

后端 未结 3 1838
感动是毒
感动是毒 2021-02-19 19:13

I am implementing a custom Cypress command in TypeScript:

// support/commands.ts
const login = () => {
    console.log(\'Logging in...\');
};

Cypress.Command         


        
相关标签:
3条回答
  • 2021-02-19 19:19

    Here is what I use and I do not have to add /// <reference types="cypress" /> at the top of every file.

    I have my custom typings under <projectroot>/cypress/support/index.d.ts

    /// <reference types="cypress" />
    
    declare namespace Cypress {
      interface Chainable<Subject> {
        getByDataTest(tag: string): Chainable<any>
      }
    }
    
    

    And my <projectroot>/cypress/tsconfig.json looks like

    {
      "compilerOptions": {
        "strict": true,
        "baseUrl": "../node_modules",
        "target": "es5",
        "lib": ["es5", "dom"],
        "typeRoots": ["./support"]
      },
      "include": ["**/*.ts"]
    }
    

    And TypeScript is finally happy

    describe('when I want to select by data test tag', () => {
      it('should select by data test tag', () => {
        cy.getByDataTest('yolo').should('exist')
      });
    });
    
    0 讨论(0)
  • 2021-02-19 19:34

    I had the same issue and all solutions I found did not work for me. Having done everything from the official Cypress documentation and other solutions here I still got the error cy.login is not a function.

    The problem was that I renamed every .js file to .ts and cypress/support/index.ts was not loaded any more, because per default Cypress only loads the JavaScript one. To fix it, you need to change it to .ts in cypress.json like that (the same with plugins file):

    {
      "supportFile": "cypress/support/index.ts",
      "pluginsFile": "cypress/plugins/index.ts"
    }
    

    You can also add the part with declare namespace Cypress {... to commands.ts instead of creating an index.d.ts file, to have the declaration and implementation in the same file

    0 讨论(0)
  • 2021-02-19 19:43

    I fixed it by adding index.d.ts file in my commands folder. In this file I added something like this:

    import { MyCustomType } from '../Types';
    
    declare global {
      namespace Cypress {
        interface Chainable<Subject = any> {
          login(): Chainable<MyCustomType>;
        }
      }
    }
    

    If You don't import or export anything, just omit global namespace declaration:

    declare namespace Cypress {
      interface Chainable<Subject = any> {
        login(): Chainable<MyCustomType>;
      }
    }
    

    Keep in mind that it won't work with Typesciprt < 2.3, becuase default generics type has to be supported.

    0 讨论(0)
提交回复
热议问题