anna

Menu

← Back to case studies

Trailhead Playwright tests.

Browser tests

reservations.spec.ts

Books the last spots, checks persistence after reload, and verifies that cancellation restores availability.

import { expect, test } from './fixtures';

const trip = 'Ember Ridge Traverse';
const guestName = 'Alex Rivera';

test.beforeEach(async ({ trailhead }) => {
  await trailhead.load();
});

test('books the last spots, persists the receipt, and reopens capacity on cancellation', async ({ page, trailhead }) => {
  const history = trailhead.reservationHistory;
  const soldOut = page.getByRole('button', { name: `Sold out: ${trip}` });

  await test.step('Book all four spots and verify the total and receipt', async () => {
    const dialog = await trailhead.openBooking(trip);
    await dialog.getByRole('textbox', { name: 'Lead guest' }).fill(guestName);
    await dialog.getByRole('spinbutton', { name: 'Group size' }).fill('4');
    await expect(dialog.getByRole('status')).toHaveText('Total: €152');
    await dialog.getByRole('button', { name: 'Confirm reservation' }).click();
    await expect(history.getByRole('status')).toHaveText('Reservation confirmed.');
    await expect(history.getByText(`${trip} · ${guestName} · 4 guests · €152`, { exact: true })).toBeVisible();
    await history.getByRole('button', { name: 'Close', exact: true }).click();
    await expect(soldOut).toBeDisabled();
  });

  await test.step('Reload and cancel the persisted reservation', async () => {
    await page.reload();
    await expect(soldOut).toBeDisabled();
    await page.getByRole('button', { name: 'My reservations' }).click();
    await history.getByRole('button', { name: `Cancel reservation: ${trip} for ${guestName}` }).click();
    await expect(history.getByRole('status')).toHaveText('Reservation cancelled.');
    await expect(history.getByRole('listitem')).toHaveCount(0);
    await history.getByRole('button', { name: 'Close', exact: true }).click();
    const reopened = await trailhead.openBooking(trip);
    await expect(reopened.getByText('4 spots available · €38 / person')).toBeVisible();
  });
});

for (const quantity of ['0', '1.5', '5', '']) {
  test(`rejects group size ${quantity || '(empty)'} and leaves reservations empty`, async ({ page, trailhead }) => {
    const dialog = await trailhead.openBooking(trip);
    await dialog.getByRole('textbox', { name: 'Lead guest' }).fill(guestName);
    const size = dialog.getByRole('spinbutton', { name: 'Group size' });
    await size.fill(quantity);
    await dialog.getByRole('button', { name: 'Confirm reservation' }).click();
    await expect(size).toBeFocused();
    await expect(size).toHaveAccessibleDescription('Enter a whole number from 1 to 4.');
    await dialog.getByRole('button', { name: 'Close', exact: true }).click();
    await page.getByRole('button', { name: 'My reservations' }).click();
    await expect(trailhead.reservationHistory.getByRole('status')).toHaveText('You have no reservations.');
  });
}

test('rejects whitespace-only guest names and focuses the invalid field', async ({ trailhead }) => {
  const dialog = await trailhead.openBooking(trip);
  const guest = dialog.getByRole('textbox', { name: 'Lead guest' });
  await guest.fill('   ');
  await dialog.getByRole('button', { name: 'Confirm reservation' }).click();
  await expect(guest).toBeFocused();
  await expect(guest).toHaveAccessibleDescription('Enter the lead guest’s name.');
  await expect(trailhead.reservationHistory).toBeHidden();
});
navigation.spec.ts

Checks responsive navigation, keyboard dismissal, and scroll locking.

import { expect, test } from './fixtures';

test('portfolio switches to a right-side menu drawer strictly below 770px', async ({ page }) => {
  await page.emulateMedia({ reducedMotion: 'reduce' });
  await page.setViewportSize({ width: 770, height: 600 });
  await page.goto('/about-me');
  const nav = page.getByRole('navigation', { name: 'Main navigation' });
  const toggle = page.getByRole('button', { name: 'Menu', exact: true });
  const menu = page.getByRole('dialog', { name: 'Menu' });
  const current = nav.getByRole('link', { name: 'About me' });
  await expect(current).toHaveAttribute('aria-current', 'page');
  await expect(toggle).toBeHidden();

  await page.setViewportSize({ width: 769, height: 600 });
  await expect(nav).toBeHidden();
  await expect(toggle).toBeVisible();
  await expect(page.getByRole('button', { name: 'Shortlist 0' })).toBeVisible();
  await toggle.click();
  await expect(menu).toHaveCSS('animation-name', 'none');
  expect(await menu.boundingBox()).toMatchObject({ x: 417, y: 0, width: 352, height: 600 });
  await expect(toggle).toHaveAttribute('aria-expanded', 'true');
  await expect(menu.getByRole('button', { name: 'Close menu' })).toBeFocused();
  await expect(page.locator('html')).toHaveCSS('overflow', 'hidden');
  await menu.getByRole('heading', { name: 'Menu' }).click();
  await expect(menu).toBeVisible();
  await page.mouse.click(5, 5);
  await expect(menu).toBeHidden();
  await expect(toggle).toBeFocused();
  await expect(page.locator('html')).not.toHaveCSS('overflow', 'hidden');

  await toggle.click();
  await page.keyboard.press('Escape');
  await expect(toggle).toHaveAttribute('aria-expanded', 'false');
  await toggle.click();
  await page.setViewportSize({ width: 770, height: 600 });
  await expect(menu).toBeHidden();
  await expect(current).toBeFocused();

  await page.setViewportSize({ width: 390, height: 600 });
  await toggle.click();
  expect(await menu.boundingBox()).toMatchObject({ x: 48, y: 0, width: 342, height: 600 });
  await menu.getByRole('link', { name: 'Case studies' }).click();
  await expect(page).toHaveURL('/case-studies');
  await expect(menu).toBeHidden();
});

for (const [width, compact] of [[390, true], [736, true], [737, false], [1200, false]] as const) {
  test(`shows the correct navigation at ${width}px`, async ({ page }) => {
    await page.setViewportSize({ width, height: 850 });
    await page.goto('/trailhead');
    const header = page.getByRole('banner');
    const nav = header.getByRole('navigation', { name: 'Main navigation' });
    const menu = header.getByRole('button', { name: 'Menu' });
    await expect(menu).toHaveCount(compact ? 1 : 0);
    await expect(nav).toHaveCount(compact ? 0 : 1);

    const logo = await header.getByRole('link', { name: 'Trailhead.' }).boundingBox();
    const rightControl = await header.getByRole('button', { name: compact ? 'Menu' : 'Sign in' }).boundingBox();
    expect(logo).not.toBeNull();
    expect(rightControl).not.toBeNull();
    expect(Math.abs(logo!.x - (width - rightControl!.x - rightControl!.width))).toBeLessThan(2);
  });
}

test('the mobile menu opens, closes with Escape, and resets after resizing', async ({ page }) => {
  await page.setViewportSize({ width: 390, height: 844 });
  await page.goto('/trailhead');
  const menu = page.getByRole('button', { name: 'Menu' });
  const nav = page.getByRole('navigation', { name: 'Main navigation' });
  const hikes = nav.getByRole('link', { name: 'Hikes' });
  const dialog = page.getByRole('dialog', { name: 'Menu' });

  await menu.click();
  await expect(page.getByRole('button', { name: 'Menu', exact: true, includeHidden: true }))
    .toHaveAttribute('aria-expanded', 'true');
  const close = dialog.getByRole('button', { name: 'Close menu' });
  await expect(close).toBeFocused();
  await page.locator('#search').evaluate((search) => search.focus());
  await expect(close).toBeFocused();
  await page.keyboard.press('Tab');
  await expect(hikes).toBeFocused();
  await page.keyboard.press('Escape');
  await expect(menu).toBeFocused();
  await expect(menu).toHaveAttribute('aria-expanded', 'false');
  await expect(nav).toBeHidden();

  await menu.click();
  await page.setViewportSize({ width: 1024, height: 844 });
  await expect(nav).toBeVisible();
  await expect(menu).toBeHidden();
  await expect(dialog).toBeHidden();
  await expect(hikes).toBeFocused();
  await page.setViewportSize({ width: 390, height: 844 });
  await expect(menu).toHaveAttribute('aria-expanded', 'false');
  await expect(nav).toBeHidden();
});

test('the footer stacks at tablet width and keeps its three navigation links on one row', async ({ page }) => {
  await page.setViewportSize({ width: 607, height: 800 });
  await page.goto('/trailhead/about');
  const footer = page.getByRole('contentinfo');
  const brand = await footer.getByRole('link', { name: 'Trailhead.' }).boundingBox();
  const nav = footer.getByRole('navigation', { name: 'Footer navigation' });
  const links = await Promise.all(['Hikes', 'About us', 'Contact'].map((name) =>
    nav.getByRole('link', { name }).boundingBox()
  ));
  const email = await footer.getByRole('link', { name: 'sevelova.an@gmail.com' }).boundingBox();

  expect(brand).not.toBeNull();
  expect(email).not.toBeNull();
  expect(links.every((link) => link !== null && link.y === links[0]?.y)).toBe(true);
  expect(links[0]!.y).toBeGreaterThan(brand!.y + brand!.height);
  expect(email!.y).toBeGreaterThan(links[0]!.y + links[0]!.height);
  expect(Math.abs(email!.x - brand!.x)).toBeLessThan(2);
});

test('wheel input cannot scroll the page behind the menu and works again after closing it', async ({ page }) => {
  await page.setViewportSize({ width: 390, height: 650 });
  await page.goto('/trailhead');
  await expect(page.getByRole('article').first()).toBeVisible();
  const menu = page.getByRole('button', { name: 'Menu' });
  await menu.click();

  const dialog = page.getByRole('dialog', { name: 'Menu' });
  const lockedPosition = await page.evaluate(() => window.scrollY);
  await expect(page.locator('html')).toHaveCSS('overflow', 'hidden');
  await page.mouse.move(190, 600);
  await page.mouse.wheel(0, 600);
  await page.evaluate(() => new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
  expect(await page.evaluate(() => window.scrollY)).toBe(lockedPosition);

  await dialog.getByRole('button', { name: 'Close menu' }).click();
  await expect(dialog).toBeHidden();
  await expect(menu).toBeFocused();
  expect(await page.evaluate(() => window.scrollY)).toBe(lockedPosition);
  await page.mouse.move(190, 600);
  await page.mouse.wheel(0, 600);
  await expect.poll(() => page.evaluate(() => window.scrollY)).toBeGreaterThan(lockedPosition);
});
accessibility.spec.ts

Runs axe checks and verifies keyboard focus when opening and closing a booking dialog.

import AxeBuilder from '@axe-core/playwright';
import { expect, test } from './fixtures';

const wcagTags = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'];

test('the catalog and reservation dialog have no axe violations in the selected WCAG rules', async ({ page, trailhead }) => {
  await trailhead.load();
  const catalog = await new AxeBuilder({ page }).withTags(wcagTags).analyze();
  expect(catalog.violations).toEqual([]);

  await trailhead.openBooking('Cedar Valley Loop');
  const dialog = await new AxeBuilder({ page }).withTags(wcagTags).analyze();
  expect(dialog.violations).toEqual([]);
});

test('a keyboard user can open and dismiss the booking and return focus to its trigger', async ({ page, trailhead }) => {
  await trailhead.load();
  await trailhead.difficulty.focus();
  await page.keyboard.press('Tab');
  await expect(page.getByRole('button', { name: 'Clear filters' })).toBeFocused();
  await page.keyboard.press('Tab');
  await expect(page.getByRole('link', { name: 'View itinerary: Cedar Valley Loop' })).toBeFocused();
  await page.keyboard.press('Tab');
  const reserve = trailhead.reserveButton('Cedar Valley Loop');
  await expect(reserve).toBeFocused();

  await page.keyboard.press('Enter');
  const dialog = page.getByRole('dialog', { name: 'Cedar Valley Loop' });
  await expect(dialog.getByRole('textbox', { name: 'Lead guest' })).toBeFocused();
  await page.keyboard.press('Escape');
  await expect(dialog).toBeHidden();
  await expect(reserve).toBeFocused();
});

API tests

reservations-api.spec.ts

Sends simultaneous reservations and checks that inventory is shared, bookings are isolated, and cancellation releases spots.

import { expect, test } from '@playwright/test';
import { randomUUID } from 'node:crypto';

test('reserves shared capacity atomically, isolates visitor history, and releases spots on cancellation', async ({ playwright, baseURL }) => {
  const first = await playwright.request.newContext({ baseURL });
  const second = await playwright.request.newContext({ baseURL });
  const attempts = [first, second].map((client, index) => ({
    client,
    data: { id: randomUUID(), tripId: 'cedar', guest: `Demo visitor ${index + 1}`, quantity: 4, total: 1 }
  }));

  try {
    expect((await first.get('/api/reservations')).status()).toBe(401);
    for (const { client } of attempts) expect((await client.get('/api/session')).status()).toBe(200);

    const invalid = await first.post('/api/reservations', { data: { ...attempts[0].data, quantity: 1.5 } });
    expect(invalid.status()).toBe(422);

    const results = await Promise.all(attempts.map(({ client, data }) => client.post('/api/reservations', { data })));
    expect(results.map((response) => response.status()).sort()).toEqual([201, 409]);
    const winnerIndex = results.findIndex((response) => response.status() === 201);
    const winner = attempts[winnerIndex];
    const other = attempts[1 - winnerIndex];

    expect(await results[winnerIndex].json()).toMatchObject({ id: winner.data.id, quantity: 4, total: 96 });
    expect(await (await winner.client.get('/api/reservations')).json()).toHaveLength(1);
    expect(await (await other.client.get('/api/reservations')).json()).toEqual([]);
    expect((await other.client.delete(`/api/reservations/${winner.data.id}`)).status()).toBe(404);

    expect((await winner.client.post('/api/reservations', { data: winner.data })).status()).toBe(200);
    expect(await (await winner.client.get('/api/reservations')).json()).toHaveLength(1);
    expect((await winner.client.delete(`/api/reservations/${winner.data.id}`)).status()).toBe(204);

    const afterCancellation = await other.client.post('/api/reservations', { data: other.data });
    expect(afterCancellation.status()).toBe(201);
  } finally {
    await Promise.all(attempts.map(async ({ client, data }) => {
      await client.delete(`/api/reservations/${data.id}`);
      await client.dispose();
    }));
  }
});
hikes-api.spec.ts

Checks hike summaries, itinerary details, and error responses for missing routes and unsupported methods.

import { expect, test } from '@playwright/test';

test('GET /api/hikes returns bookable and sold-out hike summaries as JSON', async ({ request }) => {
  const response = await request.get('/api/hikes');
  expect(response.status()).toBe(200);
  expect(response.headers()['content-type']).toContain('application/json');

  const hikes = await response.json();
  expect(hikes.map((hike) => hike.id)).toEqual(['cedar', 'ember', 'granite']);
  expect(hikes).toEqual(expect.arrayContaining([
    expect.objectContaining({ id: 'ember', difficulty: 'Moderate', price: 38, capacity: 4 }),
    expect.objectContaining({ id: 'granite', capacity: 0 })
  ]));
  expect(hikes.every((hike) => !('itinerary' in hike))).toBe(true);
});

test('GET /api/hikes/ember returns the matching summary and ordered itinerary', async ({ request }) => {
  const response = await request.get('/api/hikes/ember');
  expect(response.status()).toBe(200);
  expect(response.headers()['content-type']).toContain('application/json');

  const hike = await response.json();
  expect(hike).toMatchObject({
    id: 'ember',
    name: 'Ember Ridge Traverse',
    duration: 'About 5 hours',
    packing: expect.stringContaining('water')
  });
  expect(hike.itinerary).toMatchObject([
    { time: '08:30', title: 'Meet at the meadow gate', description: expect.any(String) },
    { time: '10:15', title: 'Reach the ridgeline', description: expect.any(String) },
    { time: '12:00', title: 'Sheltered lunch stop', description: expect.any(String) }
  ]);
});

test('GET returns a JSON 404 for an unknown hike', async ({ request }) => {
  const response = await request.get('/api/hikes/unknown');
  expect(response.status()).toBe(404);
  expect(response.headers()['content-type']).toContain('application/json');
  expect(await response.json()).toEqual({ error: 'not_found' });
});

test('POST returns 405 with the supported methods', async ({ request }) => {
  const response = await request.post('/api/hikes');
  expect(response.status()).toBe(405);
  expect(response.headers().allow).toBe('GET, HEAD');
  expect(await response.json()).toEqual({ error: 'method_not_allowed' });
});

test('HEAD returns JSON headers and an empty body', async ({ request }) => {
  const response = await request.head('/api/hikes/ember');
  expect(response.status()).toBe(200);
  expect(response.headers()['content-type']).toContain('application/json');
  expect(await response.text()).toBe('');
});

Your shortlist

Nothing selected yet. An unusual number of edge cases remain available.