Let us write actual tests. Full page screenshots. Element screenshots. Running them. Generating baselines. The full workflow from zero to passing visual tests.
import { test, expect } from '@playwright/test';
test('banking login -- full page', async ({ page }) => {
await page.goto('/banking/login');
// Wait for everything to load -- fonts, images, animations
await page.waitForLoadState('networkidle');
// Capture the entire visible viewport
await expect(page).toHaveScreenshot('login-viewport.png');
// Capture the FULL scrollable page (including below the fold)
await expect(page).toHaveScreenshot('login-fullpage.png', {
fullPage: true,
});
});You do not always need the full page. Sometimes you just want to check one component -- a navbar, a card, a sidebar. Element-level screenshots are smaller, faster, and less likely to break from unrelated changes.
import { test, expect } from '@playwright/test';
test('banking sidebar visual test', async ({ page }) => {
await page.goto('/banking');
await page.waitForLoadState('networkidle');
// Screenshot a specific element
const sidebar = page.getByTestId('sidebar');
await expect(sidebar).toHaveScreenshot('banking-sidebar.png');
});
test('login form card', async ({ page }) => {
await page.goto('/banking/login');
// Screenshot just the login card
const loginCard = page.locator('.login-card');
await expect(loginCard).toHaveScreenshot('login-card.png');
});
test('navigation header', async ({ page }) => {
await page.goto('/banking');
const header = page.getByRole('banner');
await expect(header).toHaveScreenshot('banking-header.png');
});Write your visual test with toHaveScreenshot().
Run: npx playwright test tests/visual/ -- test fails with "missing snapshot." This is normal.
Run: npx playwright test tests/visual/ --update-snapshots -- this creates the baseline images.
Run again: npx playwright test tests/visual/ -- now it passes because baseline exists.
Commit the snapshot files to git. Your team shares the same baselines.
# First run -- fails, no baselines yet
npx playwright test tests/visual/
# Generate baselines
npx playwright test tests/visual/ --update-snapshots
# Verify -- should pass now
npx playwright test tests/visual/
# Commit baselines to git
git add tests/visual/*.spec.ts-snapshots/
git commit -m "Add visual test baselines"Always review baseline screenshots before committing. Open them in an image viewer. Make sure they capture the right state -- no loading spinners, no half-loaded images, no tooltips blocking content.
Do NOT run --update-snapshots blindly. That flag accepts ALL current screenshots as the new baseline. If there is a real bug on the page, you just approved the bug as "correct." Always review the diff first.
Key Point: Start with full page screenshots, then narrow down to element screenshots. Generate baselines with --update-snapshots and commit them to git.