0

I want to create a cypress custom command that based on user arguments will add cypress action and chain them together

Now I have something like this:

Cypress.Commands.add(
  'selectButton',
  (text: string, ...actionType: ButtonActionTypes[]) => {
    let cyActions = '';

    for (let i = 0; i < actionType.length; i++) {
      const cyAction = actionType[i];
      const getActionType = getAction(text, actionType);

      if (getActionType !== null) {
        cyActions += `${getActionType}`;
      } else {
        cyActions += cyAction;
      }

      `${cy.get('button')}.${cyActions}`;
    }
  }
);

function getAction(text, action) {
  switch (action) {
    case 'click':
      'click()';
      break;
    case 'visible':
      'should("be.visible")';
      break;
    case 'disabled':
      'should("be.disabled")';
      break;
    case 'blur':
      'blur()';
      break;
    case 'contains':
      `contains(${text})`;
      break;
  }
}

But this is not working as i want. Although it is selecting buttons, but if i want to create this: cy.selectButton('Send').should('be.visible').should('be.disabled'); based on that cy.selectButton('Send', 'visible', 'disabled', 'click'); I am getting all buttons that i have on my site

Lola Ichingbola
  • 3,035
  • 3
  • 16
shivetay
  • 315
  • 4
  • 14

1 Answers1

2

You could probably handle assertions since the syntax underlying .should('be.visible') is expect(subject).to.be.visible and the .to, .be, .visible are just properties of the expect(subject) wrapper of your assertion subject.

Cypress.Commands.add(
  'selectButton',
  (text: string, ...actionTypes: ButtonActionTypes[]) => {
    let cyActions = '';

    cy.get(text).then($el => {

      const expectWrapper = expect($el)  // wraps subject for chain of assertions

      [...actionTypes].forEach(actionType => {
        expectWrapper[actionType]
      })      
  }
)

I don't know about the commands, it's a little more difficult to add those dynamically - might be impossible, since Cypress likes to set up the command queue before running it.

Lola Ichingbola
  • 3,035
  • 3
  • 16