303
303

Reputation: 1108

How do I wait for the callback passed to a Cypress custom command to finish before proceeding the test?

I have this code:

cy.visit(Cypress.env('frontendUrl'))
  .pathShould('be', '/login')
  .log('Reached')

My custom command pathShould looks like this:

Cypress.Commands.add('pathShould', (chain, path) => {
  cy.location('pathname', { timeout: 20000 }).should(chain, path);
});

In some cases the should assertion is executed, in others it isn't, like here:

enter image description here

How do I ensure that the callback of my custom command is executed completely before continuing the test?

Upvotes: 1

Views: 3283

Answers (2)

Vangelisz Ketipisz
Vangelisz Ketipisz

Reputation: 967

On a side note: it is probably an overkill to use a custom command like this, as you don't really gain anything by wrapping a one liner. Take a look at: https://docs.cypress.io/api/cypress-api/custom-commands.html#Best-Practices

Upvotes: 2

Zach Bloomquist
Zach Bloomquist

Reputation: 5871

The main issue is that there is not an assertion named be.

cy.should('be', '') won't do anything - it's not a valid assertion. You're probably looking for cy.should('eq'...)

This works for me:

Cypress.Commands.add('pathShould', (chain, path) => {
  return cy.location('pathname', { timeout: 20000 }).should(chain, path);
});

it('', () => {
  cy.visit('http://example.com')
  .pathShould('eq', '/')
  .log('Reached')
})

passing test screenshot

Upvotes: 3

Related Questions