If we want to navigate back and forward to the previous or the next URL in browser history, then the Cypress go command is the one to use.
It yields the window object after the page finishes loading. If going forward or back causes a full page refresh, Cypress will wait for the new page to load before executing the next commands.
Go Command Syntax
cy.go(direction)
cy.go(direction, options)
Arguments:
- direction(string, number):
- We can use back and forward to travel back and forth the page, and
- Also, we can use -1 and 1 to travel back and forth to a specific history position.
- Options:
- Log: To display the command in the command log.
- Timeout: Wait for cy.go(), to get finished before timing out.
Correct Use:
//same as browser forward button
cy.go('forward')
cy.go(1)
//same as browser back button
cy.go('back')
cy.go(-1)
Rules And Requirements
- It must be chained off with cy.
- The response should be of content-type: text/html.
- Require load event to fire.
- Require the response code to be 2xx after following redirect
Example Cypress Go
Let us do some practical real-time examples of the go command.
Here is the scenario:
- Visit the site https://www.programsbuzz.com.
- Click on ask a doubt.
- Click on the login.
- Navigate back and forth using the go command directions.
describe('Go Command',()=>{
before(() => {
cy.visit('https://www.programsbuzz.com')
})
it('Navigate Back And Forth Using GO Command',()=>{
cy.contains('Ask Doubt').click()
cy.get('li.menu-item--active-trail').parents('.gva_menu_main').children().last().click()
cy.go('back')
cy.go('forward')
cy.go(-1)
cy.go(1)
})
})
- We have used the parents command to click on log in.
- Here is the link https://www.programsbuzz.com/article/cypress-parents-command to know about what parents command is.
- We used the back, forward, -1, and 1 to navigate back and forth between the pages.
We can see from the command log that it has successfully navigated between pages with ease.