How to Test Animations Automatically in Playwright
Learn how to test UI animations and state machines in Playwright: disabling motion for snapshot stability, testing reduced-motion media, and waiting for springs to settle.
Core Takeaway
To test animations reliably in Playwright, test them in two modes: first, freeze or disable animations across the page to ensure deterministic visual regression snapshots; second, test interactive animation behavior by waiting for state machines to reach resting states using page.waitForFunction() or locator.toBeVisible(). Verify accessibility by emulating prefers-reduced-motion via page.emulateMedia().
The problem with animated visual regression tests
Visual regression tests that capture screenshots while an animation is in flight produce flaky failures because frames vary by a few milliseconds between runs. Playwright solves this by default with animations: 'disabled' during screenshot capture, forcing transitions to their terminal frame.
Waiting for spring physics and state machines
Unlike CSS transitions with predictable durations, physics-based springs settle when velocity drops below a threshold. To assert that a modal or drawer has finished opening before clicking inside, wait for the container's transform matrix to stabilize or check the state machine's active state property.
- Use toHaveScreenshot({ animations: 'disabled' }) to eliminate visual flakiness
- Emulate prefers-reduced-motion: 'reduce' to test accessibility modes
- Wait for state machine outputs rather than arbitrary setTimeout delays
- Assert aria-expanded and aria-checked attributes rather than raw pixel positions
Emulating prefers-reduced-motion in Playwright
Verify that your application honors user accessibility preferences by writing a dedicated test suite using page.emulateMedia({ reducedMotion: 'reduce' }). Assert that modal dialogues open immediately without sliding transitions.
Clock virtualization for timeline testing
Playwright allows developers to mock and advance system time using page.clock.fastForward('00:02'). This allows complex 5-second celebration sequences to be tested in milliseconds without hanging CI build runners.
Key Principles to Remember
- Disable CSS transitions during screenshot diffing to prevent flaky CI runs
- Assert state machine attributes (aria-expanded) rather than hardcoded sleep timers
- Test both standard and prefers-reduced-motion states with emulateMedia
- Use Playwright's clock control to advance animation time deterministically
Frequently Asked Questions
Sources
- Playwright Visual Comparisons — Microsoft
- Playwright Clock API — Microsoft