keepcalculator

06 Numbers and Powers

Mask Dynamic User Avatars in Playwright Visual Tests

Card No. 06·88761 · Updated · Standard formula, shown below

Visual regression testing with Playwright is powerful, but dynamic user avatars—whether from Gravatar, Google, or a user-uploaded service—can cause flaky tests and false failures. This guide shows you how to mask avatars so your visual tests compare only the stable layout and content, not the ever-changing images. You’ll learn a few reliable techniques, from CSS masking to route interception, and how to apply them in your Playwright tests.

What You’ll Need

  • A Playwright test project already set up (with @playwright/test installed).
  • Basic familiarity with writing Playwright tests and using page.goto(), expect(), and toHaveScreenshot().
  • Access to the application under test (either locally or via a test environment).
  • Optional: a test fixture or helper file where you can add reusable functions.

Step-by-Step

  1. Identify the avatar elements. Open your app in a browser, right-click an avatar, and choose “Inspect”. Note the CSS selector (e.g., .avatar, img[alt="user avatar"], or a data-testid attribute). If avatars appear in multiple places (header, comments, list items), list all selectors that match them.
  2. Choose a masking strategy. You have three main options:
    • CSS overlay – cover the avatar with a solid color or a placeholder. Simple, but it may not hide background images or complex layouts.
    • Route interception – block or replace the avatar image requests with a static placeholder. Works even if the avatar is loaded via JavaScript.
    • Playwright’s built-in mask option – available in toHaveScreenshot() (and page.screenshot()) since v1.33. It overlays a box on the screenshot, but it does not affect the DOM, so it’s clean and easy.
  3. Use the built-in mask option (recommended for most cases). In your test, call expect(page).toHaveScreenshot('name.png', { mask: [page.locator('.avatar')] }). Playwright will cover each matching element with a gray box in the screenshot. You can also specify maskColor to change the overlay color (e.g., '#FF00FF'). This is the simplest and most maintainable approach.
  4. If you need to mask multiple selectors, pass an array: mask: [page.locator('.avatar'), page.locator('.comment-avatar')]. You can also use a single locator that matches multiple elements, like page.locator('img.avatar').
  5. For dynamic avatars that are not direct <img> tags (e.g., background images, CSS content, or SVG), the mask option still works because it covers the element’s bounding box. Just ensure the locator points to the element that has the visual size you want to hide.
  6. If you need to mask avatars in a screenshot taken manually (not via toHaveScreenshot ), use and then compare the buffer manually if needed.
  7. For route interception (when you want to replace the image entirely), add a route in your test before navigating: await page.route('**/*avatar*', route => route.fulfill({ path: 'path/to/placeholder.png' })). Adjust the URL pattern to match your avatar endpoints. This is useful if the mask option doesn’t hide the image because of CSS that breaks layout when overlayed.
  8. For CSS overlay (if you prefer to modify the page), add a style tag: await page.addStyleTag({ content: '.avatar { visibility: hidden !important; }' }) or better, replace with a placeholder: content: '.avatar { background: #ccc !important; }' and set img.avatar { content: url('placeholder.png') !important; }. This is more invasive but can be necessary for complex layouts.
  9. Create a reusable helper. In your test file or a fixture, define a function like async function maskAvatars(page) { await page.addStyleTag({ content: '.avatar { visibility: hidden !important; }' }); } and call it in each test that needs it. This reduces repetition.
  10. Run your tests and update baselines. After applying the mask, run your visual tests with --update-snapshots to generate new baseline images. Verify that the avatars are masked and the rest of the page is unchanged.
  11. Handle avatars that load after the initial page load. If avatars appear asynchronously (e.g., after an API call), wait for them to be visible before taking the screenshot: await expect(page.locator('.avatar').first()).toBeVisible() or use await page.waitForLoadState('networkidle') if appropriate.

Common Mistakes

  • Using a too-broad selector that masks more than just avatars (e.g., img masks all images). Be specific.
  • Forgetting to wait for avatars to load before taking the screenshot, causing the mask to be applied to an empty element.
  • Using the mask option on a locator that matches zero elements – Playwright will throw an error. Always verify the locator works in the test.
  • Not updating baselines after adding the mask, leading to failures because the old baseline has avatars.
  • Using CSS display: none to hide avatars – this changes layout (element takes no space) and can break the visual comparison. Use visibility: hidden or the mask option instead.

Tips

  • For the mask option, you can set maskColor to a color that blends with your design, e.g., '#FFFFFF' for white backgrounds.
  • Use a data-testid attribute on avatar elements to make selectors robust to CSS changes.
  • If you have many tests, create a custom fixture that automatically applies the mask to every screenshot. For example, override expect to include the mask by default.
  • When using route interception, consider using a data URL for the placeholder to avoid file path issues: route.fulfill({ body: Buffer.from('...'), contentType: 'image/png' }).
  • Test your masking on a page with multiple avatars to ensure all are covered.

Troubleshooting

Mask not appearing in the screenshot? Ensure you are using Playwright v1.33 or later. Check that the locator matches elements and that they are visible. If the element has zero size (e.g., hidden), the mask won’t show.

Screenshot still fails due to avatar differences? The mask might not be applied if the avatar is a background image on a parent element. Try selecting the parent element or using a different strategy like route interception.

Route interception not working? Verify the URL pattern matches your requests. Use page.on('request') to log requests and see the exact URLs. Also ensure the route is set before navigation.

CSS overlay not working? Some CSS properties like content on img are not supported in all browsers. Use visibility: hidden on the img and add a background to the parent, or use a div with a background color.

Baseline images are now outdated? Run npx playwright test --update-snapshots to regenerate them. If you have many, review the diff to ensure only avatars changed.

Frequently Asked Questions

Can I mask avatars only in specific tests?

Yes, apply the mask option per test. You can also create a helper function and call it only in tests that need it.

Does the mask option affect the actual page?

No, it only overlays a box in the screenshot. The page’s DOM and layout remain unchanged.

What if my avatars are loaded from a CDN with random URLs?

Use a locator based on the element’s class or attribute, not the URL. The mask option doesn’t care about the image source.

Can I mask avatars in a full-page screenshot?

Yes, the mask option works with fullPage: true in toHaveScreenshot() or page.screenshot().

Is there a way to mask all images, not just avatars?

Yes, use a locator like img or [class*='image'], but be cautious as it may hide other meaningful images.

What if the avatar is a CSS background on a div?

Use a locator for that div and apply the mask. The mask covers the entire element box, hiding the background.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →