1

I'm using Cypress 9.5.3 and Typescript 4.5.

Is there a way to create custom commands hierarchically? As a result I'd like to type (as an example):

cy.loginAs.admin();

Currently I can only write a command:

cy.loginAsAdmin();

Also support from VSC is important for me.

EDIT 1

I'd like to use those nested commands like this:

cy.loginAs.admin();
cy.loginAs.operator();
cy.loginAs.user();
3
  • What exactly are you trying to do? You could always write your custom command to have different flows and take in the role as a parameter. Something like cy.loginAs('admin'); or cy.loginAs('user'); Commented Mar 29, 2022 at 14:07
  • This is just example. I extended question. Commented Mar 29, 2022 at 14:21
  • You would reverse the order, since Cypress commands pass a "subject" down the chain (not up) - cy.asAdmin().login(). But your example is too trivial what would admin() do but return the string "admin"? Does it need to check context in some way? Commented Mar 29, 2022 at 20:39

2 Answers 2

2

I think the best way to handle this would be to add the role as a parameter to your custom command.

Cypress.Commands.add('loginAs', (role: string) => {
  switch (role) {
    case 'Admin':
      // code
    case 'Operator':
      // code
    case 'User':
      // code
    default:
      // code
  }
});

cy.loginAs('admin');
cy.loginAs('operator');
cy.loginAs('user');

If you knew you had a limited number of roles, you could create an enum.

enum Roles {
  Admin,
  Operator,
  User
}

Cypress.Commands.add('loginAs', (role: Roles) => {
  //code 
})

cy.loginAs(Roles.Admin);
cy.loginAs(Roles.Operator);
cy.loginAs(Roles.User);

Using a switch statement is just a suggestion, but depending on how different the flows are, you may have more success with a different method.

Sign up to request clarification or add additional context in comments.

Comments

0

It's possible to add nested commands by extending the global "cy" object.

From the Cypress Docs:

Public interface for the global "cy" object. If you want to add a custom property to this object, you should extend this interface. @see https://on.cypress.io/typescript#Types-for-custom-commands

link to Cypress Docs

Example based on your question:

// cypress/support/loginAs.ts
function admin () {

}

function operator () {

}

export default {
  admin,
  operator,
}

// cypress/support/index.ts
import loginAs from './loginAs';

declare global {
  namespace Cypress {
    interface cy {
      loginAs: typeof loginAs 
   }
  }
}

cy.loginAs = loginAs;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.