DEV Community

Jordan Powell for Cypress

Posted on

Typescript Support For Cypress

For someone who has worked with Typescript for the past 5+ years, I really miss it when it's not there. I find adding types to my javascript code a nice comfort. Writing automated tests with Cypress is no exception. With that being said, adding Typescript support to your Cypress applications is easy peasy!

Getting Started

Cypress ships with official type declarations for TypeScript. This allows you to write your tests in TypeScript. The first thing we need to do is install the typescript dependency.

yarn add --dev typescript
Enter fullscreen mode Exit fullscreen mode

Next we need to update our tsconfig.json file with the following configuration:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": ["cypress"]
  },
  "include": ["**/*.ts"]
}
Enter fullscreen mode Exit fullscreen mode

Finally we need to rename all of our .spec.js integration files to .spec.ts.

Custom Commands

If you are like me you've found the path to this point super simple! However, if your application is using Cypress's Custom Commands API your Cypress application is now angry.

Typescript Error

Don't worry this is easy to fix! Let's open the file that contains our custom commands (usually support/commands.ts). This file should contain all of your commands as well as a Cypress namespace with a Chainable Interface. It is in this Interface we will add a reference to our custom command(s).

declare namespace Cypress {
  interface Chainable<Subject> {
    getBySel(selector: string): Chainable<Element>
  }
}

Cypress.Commands.add('getBySel', (selector: string, ...args: any[]): Cypress.CanReturnChainable => {
  return cy.get(`[data-test=${selector}]`, ...args)
})
Enter fullscreen mode Exit fullscreen mode

And voilà our Cypress application is happy and now has full support for Typescript!

More Resources

Top comments (0)