0
0
Cypresstesting~15 mins

cy.go() for browser history in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify browser history navigation using cy.go()
Preconditions (2)
Step 1: Visit the homepage at '/home'
Step 2: Click the link to navigate to the About page at '/about'
Step 3: Verify the URL is '/about'
Step 4: Use cy.go('back') to navigate back to the homepage
Step 5: Verify the URL is '/home'
Step 6: Use cy.go('forward') to navigate forward to the About page
Step 7: Verify the URL is '/about'
✅ Expected Result: The browser navigates back and forward correctly using cy.go(), and the URL updates accordingly.
Automation Requirements - Cypress
Assertions Needed:
URL is '/about' after navigation
URL is '/home' after going back
URL is '/about' after going forward
Best Practices:
Use cy.visit() to open pages
Use cy.get() with clear selectors for clicking links
Use cy.url().should() for URL assertions
Use cy.go() with 'back' and 'forward' arguments
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('Browser history navigation with cy.go()', () => {
  it('should navigate back and forward correctly', () => {
    cy.visit('/home');
    cy.get('a[href="/about"]').click();
    cy.url().should('include', '/about');

    cy.go('back');
    cy.url().should('include', '/home');

    cy.go('forward');
    cy.url().should('include', '/about');
  });
});

The test starts by visiting the homepage using cy.visit('/home'). Then it clicks the About page link using a clear CSS selector a[href="/about"]. After clicking, it asserts the URL includes '/about' to confirm navigation.

Next, cy.go('back') simulates the browser back button, and the test asserts the URL returns to '/home'. Then cy.go('forward') simulates the forward button, and the URL is checked again to confirm it is '/about'.

This approach uses Cypress best practices: clear selectors, URL assertions, and no hardcoded waits, relying on Cypress's automatic waiting for commands to complete.

Common Mistakes - 3 Pitfalls
Using cy.go() without verifying URL changes
Using hardcoded waits like cy.wait(2000) before cy.go()
{'mistake': "Using vague selectors like cy.get('a').click()", 'why_bad': 'This can click the wrong link if multiple anchors exist, causing flaky tests.', 'correct_approach': 'Use specific selectors like cy.get(\'a[href="/about"]\') to target the correct link.'}
Bonus Challenge

Now add data-driven testing with 3 different page pairs to test back and forward navigation.

Show Hint