How to wait my custom command finish, then executing remaining Cypress commands

Viewed 1185

I'm getting trouble with Cypress asynchronous mechanism. I have a custom command that is placed in this file

class HeaderPage {

    shopLink = 'a[href="/angularpractice/shop"]'
    homeLink = ''

    navigateToShopPage() {
        cy.get(this.shopLink).click()
    }

    sshToServer() {
        setTimeout(() => {
            console.log('Connecting')
        }, 5000)
        console.log('Connected')
    }
}

export default HeaderPage

The function sshToServer is simulated to pause 5000ms. So I want Cypress remaining test will be hold and wait for this function completed. How can I do that? Thanks in advance.

import HeaderPage from "../support/pageObjects/HeaderPage"

describe('Vefiry Alert and Confirm box', () => {

    const headerPage = new HeaderPage()

    it('Access home page', () => {
        cy.visit(Cypress.env('url') + 'AutomationPractice/')
    });

    it('SSH to server', () => {
        headerPage.sshToServer()
    });

    it('Verify content of Alert', () => {
        cy.get('#alertbtn').click()
        cy.on('window:alert', (alert) => {
            expect(alert).to.equal('Hello , share this practice page and share your knowledge')
        })
    });
2 Answers

You can issue a new cy.wrap command with a value null and calling your async function in the .then function. Cypress will resolve that async function automatically and then move on to the next test.

First, you should convert your sshToServer method to an async(promise) function:

sshToServer() {
  console.log('Connecting');
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Connected');
      resolve();
    }, 5000);
  });
}

Then, in your spec:

it('SSH to server', { defaultCommandTimeout: 5000 }, () => {
  cy.wrap(null).then(() => headerPage.sshToServer());
});

Note that I have also used a bigger for the spec defaultCommandTimeout since the default timeout is 4 seconds which is shorter than your sshToServer method and would cause the test to fail if not using a bigger timeout.

Sorry for late answer but i think this is the easiest way to do it cy.wait(milliseconds)

Related