1

i am working on a cypress project and I am trying to create a custom command which resolves promise and returns text on the passed locator.

export default class QuickRegisterPage {
  emailAddressText() {
    return cy.get('#emailAddress');
  }

public createNewUser() {
    cy.getQuickRegisterUrl().then(url => {
      cy.visit(url);
      text = cy.getText(this.emailAddressText());
      cy.log(text);  
      });
}


Cypress.Commands.add(
  'getText',
  (element: Cypress.Chainable<JQuery<HTMLElement>>) => {
    element.scrollIntoView();
    element.then(ele => {
      const text = ele.text();
      return text;
    });
  }
);

declare namespace Cypress {
  interface Chainable<Subject = any> {
    getText(element: Cypress.Chainable<JQuery<HTMLElement>>): string;
  }
}

when I am calling cy.getText() nothing is happening it's just sitting there and not returning the text.

can someone help me to resolve this.

1 Answers1

1

cy command is asynchronous so you should access its result in then block. Technically, you can return a string from a cy custom command but it's not recommended because of api consistency.

I'd write it as a child custom command

declare namespace Cypress {
  interface Chainable {
    getText(): Chainable<string>;
  }
}
  Cypress.Commands.add('getText', { prevSubject: 'element' }, 
    ($element: JQuery<HTMLElement>) => {
      cy.wrap($element).scrollIntoView()
      return cy.wrap($element).invoke('text')
    }
  )

How it's used

cy.get('#emailAddress')
      .getText()
      .then(text => console.log('Email Address ', text))
Hung Tran
  • 1,595
  • 2
  • 17
  • 17
  • `Cypress.Commands.add('getText', { prevSubject: 'element' }, ($element: JQuery) => { cy.wrap($element).scrollIntoView() return cy.wrap($element).invoke('text') } )` where exactly you are passing 'text' as an argument to the custom command so that you can use it in invoke. –  Nov 01 '19 at 12:50
  • 1
    invoke('text') - is to call text() function on $element which is #emailAdrress element. The $element comes from cy.get() because it's the parent command of cy.getText(). – Hung Tran Nov 01 '19 at 12:59
  • as I am using the typescript, what will be the cypress chainable interface to write, if we used child commands as you showed? –  Nov 01 '19 at 13:19
  • 1
    Just as same as the piece of code above, I'm using typescript too. Updated the type declaration – Hung Tran Nov 01 '19 at 13:28