Cypress wait command is used to make a step wait for several milliseconds or wait for an aliased resource to finish the process and move on to next.
Syntax:
cy.wait(time)
cy.wait(alias)
cy.wait(aliases)
cy.wait(time, options)
cy.wait(alias, options)
cy.wait(aliases, options)
Some of the options we can include in the command can be a timeout, log, etc.
- Log: To display the command in the command log.
- Timeout: Wait for some particular thing to get finished before timing out.
- Alias: pass in the aliased resource.
- Options: Can pass options object to change the default normal behavior of the cy.wait().
Correct Use:
cy.wait(1000)
Waits for 1 second before moving onto the following line.
cy.wait('@aliasname')
Waits for the aliased resource to finish what it is supposed to do and move on to next.
Yields of wait():
When given time:
- When provided with time inside, wait yields the same subject from the previous command.
When given alias:
- Yields an object containing the HTTP request and response properties of the request.
Let us see it in action then.
Timed Wait:
describe('URL Command',()=> {
it('Should load the url',()=>{
cy.visit('/')
cy.wait(1000)
cy.url().should('include','/user/login')
cy.url().should('contain',Cypress.config().baseUrl)
cy.url().should('eq',Cypress.config().baseUrl)
cy.wait(2000)
cy.location('href').should('include','/user/login')
cy.location('href').should('contain',Cypress.config().baseUrl)
cy.location('href').should('eq',Cypress.config().baseUrl)
})
})
- So we are asserting URLs here, and we have added a wait time of 1 second after the visit and 2 seconds before proceeding to the location command.
- It has imposed wait() for the provided time needed after the visit and before moving onto location command.
Aliased Wait:
describe('Intercepting Gorestapi',()=>{
it('Visiting Gorestapi',()=>{
cy.visit('https://gorest.co.in/')
})
it('Intercepting Route of users',()=>{
cy.intercept({path : '/public/v1/users' }).as('aPIntercept')
cy.get("table:nth-of-type(1) a[href = 'https://gorest.co.in/public/v1/users']").click({force: true})
cy.wait('@aPIntercept').then(interception => {
cy.log(JSON.stringify(interception))
console.log(JSON.stringify(interception))
})
})
})
- Aliased wait, as we used here @aPIntercept delays for the route aliased to respond and then proceeds to intercept without changing or stubbing its response.
- So in this way, we can access the users intercepted.
- Which will log the requested response.
We can see that the aliased wait has been initialized until the response gets intercepted.
Timeouts: The default timeout for just providing the cy.wait() is 5000ms.
Related Content
Tags