|
| 1 | +import type { Page } from '@playwright/test'; |
| 2 | +import { test, expect } from '@playwright/test'; |
| 3 | + |
| 4 | +const HERO_BANNER_H1 = 'HERO_BANNER_H1'; |
| 5 | + |
| 6 | +const someRandomPagesWithHashLinks = [ |
| 7 | + { title: 'Home', path: '/' }, |
| 8 | + { title: 'About', path: '/about' }, |
| 9 | + { title: 'Corporate Sponsorship', path: '/sponsorship' }, |
| 10 | +]; |
| 11 | + |
| 12 | +const makeHashLinkVisible = async ({ page, hashId }: { page: Page; hashId: string }) => { |
| 13 | + // Locate the heading element relevant to the hashlink |
| 14 | + const heading = page.locator(`#${hashId}`); |
| 15 | + |
| 16 | + // Scroll heading into view |
| 17 | + await heading.scrollIntoViewIfNeeded(); |
| 18 | + |
| 19 | + // Hover over the heading to make the hash link visible |
| 20 | + await heading.hover(); |
| 21 | +}; |
| 22 | + |
| 23 | +test.describe('Hash Links', () => { |
| 24 | + for (const { title, path } of someRandomPagesWithHashLinks) { |
| 25 | + test(`on ${title} page, will be invisible until hovered and change route when clicked`, async ({ |
| 26 | + page, |
| 27 | + browserName, |
| 28 | + }) => { |
| 29 | + await page.goto(path); |
| 30 | + |
| 31 | + // Wait for navigation to complete |
| 32 | + await expect( |
| 33 | + page.getByTestId(browserName === 'chromium' ? 'Desktop Nav' : 'Mobile Nav Container'), |
| 34 | + ).toBeVisible(); |
| 35 | + await expect(page).toHaveURL(new RegExp(path)); |
| 36 | + |
| 37 | + // Verify hero banner is visible |
| 38 | + await expect(page.getByTestId(HERO_BANNER_H1).first()).toBeVisible(); |
| 39 | + |
| 40 | + // Get all hash links on the page |
| 41 | + const hashLinks = await page.getByTestId('Hash Link').all(); |
| 42 | + |
| 43 | + for (const link of hashLinks) { |
| 44 | + const hash = await link.getAttribute('href'); |
| 45 | + |
| 46 | + // This is to satiate TS |
| 47 | + // eslint-disable-next-line playwright/no-conditional-in-test |
| 48 | + if (!hash) continue; |
| 49 | + |
| 50 | + const hashId = hash.replace(/^.*#/, ''); |
| 51 | + |
| 52 | + await expect(link).toBeHidden(); |
| 53 | + |
| 54 | + await makeHashLinkVisible({ page, hashId }); |
| 55 | + |
| 56 | + await expect(link).toBeVisible(); |
| 57 | + |
| 58 | + // On mobile safari, clicking elements positioned outside viewport can fail |
| 59 | + // Use evaluate to navigate directly by clicking via JavaScript |
| 60 | + await link.evaluate((el: HTMLAnchorElement) => el.click()); |
| 61 | + |
| 62 | + // Verify URL includes the hash |
| 63 | + await expect(page).toHaveURL(new RegExp(`${path}#${hashId}`)); |
| 64 | + } |
| 65 | + }); |
| 66 | + } |
| 67 | +}); |
0 commit comments