Search code examples
testingcypressui-automationpageobjects

calling variables from different commands in cypress page object modal tests


I am using Cypress with page object model in my project.

I have 2 commands in homepage.js :

One to get custId from header section & the other to get custId on footer of the page.

Now I need to check if these two custId match. how can I achieve this as the scope of variables are limited to there respective then blocks.

HomePage.js

--------Command 1-------------------

getcustomerIdOnHeaderSection()

{
     cy.get(custId locator).then($id =>{

     var headerCustomerid = $id.text().trim();

})

}

----------------command 2------------------------

getcustomerIdOnFooterSection()

{
     cy.get(custId locator).then($id =>{

     var footerCustomerid = $id.text().trim();

})

}

I want to check headerCustomerid == footerCustomerid


Solution

  • Returning the cy chains will yield Chainable<String> variables. You can easily compare these like you would other elements.

    // HomePage.js
    getcustomerIdOnHeaderSection(){
      return cy.get('foo').invoke('text').invoke('trim');
    }
    
    getcustomerIdOnFooterSection() {
      return cy.get('bar').invoke('text').invoke('trim');
    }
    
    // Test.js
    it('tests', () => {
      const hp = new HomePage();
      hp.getcustomerIdOnHeaderSection().then(($headerText) => {
        hp.getcustomerIdOnFooterSection().should('have.text', $headerText);
      });
    });