Cypress TypeScript Custom Commands

Profile picture for user arilio666

Cypress is a popular web application end-to-end testing framework. It includes a robust collection of APIs for interacting with web pages and performing various activities. Cypress's ability to develop custom instructions to increase its capabilities is crucial.

Follow these steps to create custom commands in Cypress using TypeScript:

1.) Make a command.ts file in the cypress/support directory. This is where you'll write your commands.

Cypress TypeScript Custom Commands

2.) Use the Cypress.Commands.add a function to define your custom command. Assume you want to create a custom command to log in to your application. You may put it this way:

Cypress.Commands.add("login", (email: string, password: string) => {
   cy.visit("https://www.programsbuzz.com/user/login");
   cy.get("#edit-name").type(email);
   cy.get("#edit-pass").type(password);
 });

3.) Create an index.d.ts file and paste the following:

export {}
declare global {
   namespace Cypress {
       interface Chainable {
           login(email:string, password:string): Chainable<void>;
       }
   }
}

4.) Save the file and import it into your cypress/support/e2e.js file as follows:

import "./command";

5.) Now you can use your custom command in your tests like this:

describe ('Test', function(){
   it('visit',function(){
       cy.login("MonkeyDLuffy","luffy@2R");
       
   })
})

Cypress TypeScript Custom Commands