Cypress Typescript - biswajitsundara/Cypress GitHub Wiki

Cypress can be easily integrated with Type Script

1. Create an empty folder

mkdir demoproject

This will create an empty folder with name demoproject

2. Convert the project to node project

npm init --y

This will create package.json file with default options.

3. Install cypress

npm install cypress

This will install the latest cypress version and the dependency will be added to package.json file.

4. Then open cypress so that the skeleton will be populated

node_modules/.bin/cypress open

The cypress test runner will be opened and it will populate the default cypress folder structure.

5. Create a dummy test with .js extension

Create a test file under integration folder e.g cypress/integration/basic.js

describe('demo test suite', ()=>{

   it('demo test case',()=>{
    
      cy.log('Hello world');
   })

})

6. Install typescript

  • npm install typescript
  • npm install @types/node

This will install the typescript and add the dependency to package.json file

7. Add index.ts

Change the file extension plugins/index.js to index.ts below code should be already available.

// cypress/plugins/index.ts

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

/**
 * @type {Cypress.PluginConfig}
 */
module.exports = (on, config) => {
}

8. Add tsconfig.json

tsc --init

This will generate tsconfig.json file with below codes.

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["es5", "dom"],
    "types": ["cypress","node"]
  },
  "include": ["**/*.ts"]
}

9. Create the typescript test

  • Change the file extension from .js to .ts for the file created at step #5
  • cypress/integration/basic.ts
  • Launch the test runner and run the file.
  • It should work fine.

The package.json dependecy section should look like below.

"dependencies": {
    "@types/node": "^14.6.2",
    "cypress": "^4.12.1",
    "typescript": "^4.0.2"
  }

We can initiate tsconfig.json file with cypress/typesscript options also

tsc --init --types cypress

This will generate the file as below.

 {
  "compilerOptions": {
    "target": "es5",                         
    "module": "commonjs",                     
     "lib": ["es5","dom"],                       
    "types": ["cypress","node"],                     
    "esModuleInterop": true,                  
    
    /* Advanced Options */
    "skipLibCheck": true,                    
    "forceConsistentCasingInFileNames": true  
  },
  "compileOnSave": false,
  "include": [
    "**/*.ts"
  ]
}

Google search test

it('should perform basic google search', () => {

    cy.visit("https://google.co.in");
    cy.get('[name="q"]')
      .type('subscribe')
      .type('{enter}');
       
  });

});

Reference

https://docs.cypress.io/guides/tooling/typescript-support.html#Install-TypeScript
https://basarat.gitbook.io/typescript/intro-1/cypress
https://github.com/TheBrainFamily/cypress-cucumber-preprocessor#typeScript-support

⚠️ **GitHub.com Fallback** ⚠️