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/testinstalled). - Basic familiarity with writing Playwright tests and using
page.goto(),expect(), andtoHaveScreenshot(). - 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
- 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 adata-testidattribute). If avatars appear in multiple places (header, comments, list items), list all selectors that match them. - 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
maskoption – available intoHaveScreenshot()(andpage.screenshot()) since v1.33. It overlays a box on the screenshot, but it does not affect the DOM, so it’s clean and easy.
- 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 specifymaskColorto change the overlay color (e.g.,'#FF00FF'). This is the simplest and most maintainable approach. - 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, likepage.locator('img.avatar'). - For dynamic avatars that are not direct
<img>tags (e.g., background images, CSScontent, 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. - If you need to mask avatars in a screenshot taken manually (not via toHaveScreenshot ), use and then compare the buffer manually if needed.
- 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. - 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 setimg.avatar { content: url('placeholder.png') !important; }. This is more invasive but can be necessary for complex layouts. - 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. - Run your tests and update baselines. After applying the mask, run your visual tests with
--update-snapshotsto generate new baseline images. Verify that the avatars are masked and the rest of the page is unchanged. - 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 useawait page.waitForLoadState('networkidle')if appropriate.
Common Mistakes
- Using a too-broad selector that masks more than just avatars (e.g.,
imgmasks 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: noneto hide avatars – this changes layout (element takes no space) and can break the visual comparison. Usevisibility: hiddenor the mask option instead.
Tips
- For the mask option, you can set
maskColorto a color that blends with your design, e.g.,'#FFFFFF'for white backgrounds. - Use a
data-testidattribute 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
expectto 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
- Unix Time Converter Milliseconds: How It Works28500000:00:00
- Convert hr:min to min: Quick Guide150 min
- Sales Growth Rate: Formula & How to Calculate20.00 %
- 1 mm to cm Calculator: Quick Conversion2.50 cm
- Multiple Services Operator Meaning & How to Use It12.56 m3
- Calculate Days From Now: Date Difference Tool