Handling Animations & Loading States in Visual Tests
In this article
Visual regression testing compares screenshots of your UI to catch unintended changes. Animations and loading spinners are the most common cause of false failures, because the page looks different in every frame. This guide shows you how to stabilize those states so your visual tests are reliable and meaningful.
What You'll Need
- A visual testing tool (e.g., Percy, Chromatic, Applitools) or a screenshot-based test runner (e.g., Playwright, Cypress with visual plugins).
- Access to your application's code to add test hooks or disable animations.
- Basic understanding of your test framework's wait and assertion methods.
Step-by-Step
- Identify animation sources. List all CSS transitions, keyframe animations, JavaScript-driven animations (like carousels or countdowns), and loading spinners in the components you test. Common culprits: hover effects, modal fade-ins, skeleton loaders, and progress bars.
- Disable CSS animations globally in test environments. The simplest approach is to inject a style that turns off all transitions and animations. In Playwright or Cypress, add this before each test:
const style = document.createElement('style'); style.textContent = '* { transition: none !important; animation: none !important; }'; document.head.appendChild(style);
This instantly stabilizes most CSS-based motion without touching your app code. - Use a test hook to pause JavaScript animations. For JS-driven animations (like a library that animates numbers or a custom carousel), add a global flag. In your app, check
window.__DISABLE_ANIMATIONS__and skip the animation logic. In tests, set that flag before loading the page. - Wait for loading states to finish. If you cannot disable a spinner, wait for it to disappear. Use an explicit wait for the element to be hidden or for the content to appear. In Playwright:
await page.waitForSelector('.spinner', { state: 'detached' });In Cypress:cy.get('.spinner').should('not.exist'); - Use network stubbing to control slow responses. If a loading state only appears when a request is slow, stub the network to return instantly or with a fixed delay. In Cypress:
cy.intercept('/api/data', { fixture: 'data.json' }).as('getData');Then wait for the response before taking a screenshot. - Freeze time for time-based UI. If your UI shows a clock, countdown, or relative timestamps, freeze the system time. Playwright has
page.clock.install()andpage.clock.fixedTime(). In Cypress, usecy.clock()andcy.tick()to control time precisely. - Take screenshots only after a stable state. After disabling animations and waiting for loaders, add a small settle delay (e.g., 500ms) before capturing. This allows fonts, images, and any remaining async work to finish. Most visual testing tools have a
waitForTimeoutordelayoption. - Set a consistent viewport and device scale factor. Visual tests are sensitive to viewport size and device pixel ratio. Always set these explicitly in your test configuration to avoid cross-environment differences.
- Use a dedicated test environment. Run visual tests against a build where animations are disabled by default (e.g., a
testquery parameter or a feature flag). This avoids injecting styles in every test and keeps your production code untouched. - Review and approve baseline screenshots. When you first run visual tests, review the generated baseline images. Make sure they show the intended final state, not a mid-animation frame. If a baseline is wrong, delete it and re-run to create a correct one.
Common Mistakes
- Relying on fixed sleeps. Using
wait(2000)is fragile; the animation might finish in 1 second or take 3 on a slow CI machine. Always use conditional waits. - Disabling animations only in CSS. Many UI libraries animate via JavaScript (e.g., React Transition Group, Framer Motion). CSS overrides won't stop those. You need to also disable JS animations.
- Forgetting about infinite animations. A pulsing dot or a spinning loader never ends. If you can't disable it, you must wait for it to be removed, not just for it to settle.
- Taking screenshots too early. Even after the loader disappears, images and fonts may still load. Always wait for the
loadevent or use a network idle wait. - Ignoring the baseline. If your baseline screenshot contains a half-finished animation, every future run will be compared to that incorrect state, causing false failures or hiding real regressions.
Tips
- Create a helper function that prepares the page for visual testing (disables animations, waits for loaders, sets viewport) and call it at the start of every visual test.
- Use test IDs (e.g.,
data-testid="spinner") to reliably select loading elements, instead of relying on CSS classes that may change. - If your visual testing tool supports it, use a freeze or pause feature that stops all animations at a specific frame.
- For complex components like charts or maps, consider mocking the data to a fixed set so the rendering is deterministic.
- Run visual tests in a Docker container with the same OS and browser version as your CI to reduce environment-related differences.
Troubleshooting
- Still seeing flaky failures after disabling animations? Check if the issue is caused by a web font loading. Use
document.fonts.readyin your wait logic, or preload fonts in the test. - Spinner disappears but the content is not stable. The content may be loading asynchronously in chunks. Wait for a specific element that indicates completion, such as a table row count or a final text.
- Animations are not disabled by the CSS injection. Verify the injection runs before the page scripts. Use
addInitScriptin Playwright orbefore:loadin Cypress to inject early. - Time-freezing breaks the app. Some apps use
Date.now()for logic beyond display. Freezing time can cause infinite loops or errors. In that case, only freeze time for the visual snapshot, then restore it. - Visual differences between local and CI. Ensure both use the same browser, viewport, and OS. Also check if your local machine has a different GPU rendering that affects anti-aliasing.
- Baseline images are corrupted. Delete the baseline and re-generate it. If it happens often, your test is likely not waiting for a stable state.
Frequently Asked Questions
Why do I need to disable animations at all?
Animations change the pixels every frame. A screenshot taken at different times will show different frames, causing false differences even though the UI is functionally correct.
Can I just wait for the animation to finish instead of disabling it?
Yes, if the animation is finite and short. But it's slower, and if the animation duration varies (e.g., based on network speed), it's unreliable. Disabling is faster and more deterministic.
What about loading spinners that never disappear?
If a spinner is always visible (e.g., a pulsing icon), you must either disable it via CSS or test hook, or exclude that element from the screenshot using a masking region.
How do I handle skeleton screens?
Skeleton loaders are usually CSS animations. Disable them with the global CSS override, or wait for the skeleton to be replaced by actual content.
Should I test loading states at all?
Yes, but you should test them separately. For example, take a screenshot of the spinner state by stubbing a slow network, then another screenshot after the content loads. This verifies both states are correct.
My visual tests pass locally but fail in CI. Why?
Differences in CPU speed, network latency, or font rendering can cause timing differences. Use explicit waits instead of sleeps, and ensure your CI environment uses the same browser and OS as your local machine.