How to Use cy.go for Navigation in Cypress Tests
Use
cy.go() in Cypress to navigate through the browser's history stack. You can pass a number to move forward or backward (e.g., cy.go(-1) goes back one page), or use strings like 'back' or 'forward' for navigation.Syntax
The cy.go() command controls browser history navigation. It accepts either a number or a string:
cy.go(number): Moves forward or backward in history by the given number. Negative numbers go back, positive go forward.cy.go('back'): Equivalent tocy.go(-1), goes back one page.cy.go('forward'): Equivalent tocy.go(1), goes forward one page.
javascript
cy.go(-1) // Go back one page cy.go(1) // Go forward one page cy.go('back') // Go back one page cy.go('forward') // Go forward one page
Example
This example shows how to visit two pages and then use cy.go() to navigate back and forward in the browser history.
javascript
describe('cy.go navigation example', () => { it('navigates back and forward in browser history', () => { cy.visit('https://example.cypress.io') cy.contains('type').click() // Navigate to a new page cy.url().should('include', '/commands/actions') cy.go('back') // Go back to previous page cy.url().should('eq', 'https://example.cypress.io/') cy.go(1) // Go forward to next page cy.url().should('include', '/commands/actions') }) })
Output
Test passes if navigation works correctly and URLs match expected pages.
Common Pitfalls
Common mistakes when using cy.go() include:
- Trying to go forward when there is no forward history, which causes the command to do nothing.
- Using
cy.go()without visiting multiple pages first, so navigation has no effect. - Not waiting for page loads after navigation, which can cause flaky tests.
Always ensure your test visits multiple pages before using cy.go() and use assertions to confirm navigation.
javascript
/* Wrong: Using cy.go() without navigation history */ cy.visit('https://example.cypress.io') cy.go('back') // Does nothing, no previous page /* Right: Navigate first, then use cy.go() */ cy.visit('https://example.cypress.io') cy.contains('type').click() cy.go('back') // Works as expected
Quick Reference
| Usage | Description |
|---|---|
| cy.go(-1) | Go back one page in browser history |
| cy.go(1) | Go forward one page in browser history |
| cy.go('back') | Alias for going back one page |
| cy.go('forward') | Alias for going forward one page |
Key Takeaways
Use cy.go() to navigate browser history by passing a number or 'back'/'forward' strings.
Ensure your test visits multiple pages before using cy.go() to have navigation history.
Always add assertions after cy.go() to verify the page loaded correctly.
cy.go(-1) and cy.go('back') do the same thing; similarly for forward navigation.
Avoid using cy.go() when no forward or backward history exists to prevent no-op commands.