0
0
Cypresstesting~5 mins

cy.go() for browser history in Cypress

Choose your learning style9 modes available
Introduction

We use cy.go() to move back or forward in the browser history during tests. It helps check if navigation works like when a user clicks back or forward buttons.

To test if the back button returns to the previous page correctly.
To verify forward navigation after going back in history.
To simulate user clicking browser navigation buttons in automated tests.
To check if page state updates properly when moving through history.
To test multi-step navigation flows in a web app.
Syntax
Cypress
cy.go(directionOrNumber)

// directionOrNumber can be:
// 'back' or -1 to go back one page
// 'forward' or 1 to go forward one page
// any number to go that many steps in history

You can use either a string like 'back' or a number like -1 to go back one page.

Using 0 reloads the current page.

Examples
Goes back one page in browser history.
Cypress
cy.go('back')
Also goes back one page, using a number instead of a string.
Cypress
cy.go(-1)
Goes forward one page in browser history.
Cypress
cy.go('forward')
Goes forward two pages in history if possible.
Cypress
cy.go(2)
Sample Program

This test visits a page, clicks a link to go to a new page, then uses cy.go('back') to go back to the first page and checks the URL. Then it uses cy.go('forward') to go forward again and checks the URL.

Cypress
describe('Test browser history with cy.go()', () => {
  it('should navigate back and forward correctly', () => {
    cy.visit('https://example.cypress.io')
    cy.contains('type').click() // navigate to a new page
    cy.url().should('include', '/commands/actions')

    cy.go('back')
    cy.url().should('eq', 'https://example.cypress.io/')

    cy.go('forward')
    cy.url().should('include', '/commands/actions')
  })
})
OutputSuccess
Important Notes

Make sure the pages you navigate between are in the same domain to avoid cross-origin errors.

Use cy.url() assertions after cy.go() to confirm navigation worked.

Using cy.go(0) reloads the current page, which can be useful for testing refresh behavior.

Summary

cy.go() moves through browser history like back and forward buttons.

You can use strings ('back', 'forward') or numbers (-1, 1) to control navigation.

Always check the URL or page content after using cy.go() to confirm the page changed as expected.