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.
cy.go() for browser history in 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.
cy.go('back')cy.go(-1)cy.go('forward')cy.go(2)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.
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') }) })
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.
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.