Member-only story
How to Mask Dynamic Elements in Automated Visual Tests
To achieve reliable visual testing, it’s crucial to prevent unreliable tests by effectively hiding dynamic parts of your application.
When dealing with elements prone to change, like ad banners, moving text inputs, GIFs, and user cursors, it’s essential to use dynamic element masking. This means hiding these elements before taking screenshots during testing to avoid false results due to dynamic content.
Let’s use an example and imagine we want to assess the layout of the Facebook Stories section through visual testing.
The challenge here is that the images and titles in the stories tray element will differ whenever you reload the page. This isn’t ideal for visual testing.
Modern testing frameworks provide methods for this. For instance, Playwright lets you hide specific page elements when taking screenshots by completely covering its bounding box with a #FF00FF color.
Let’s try to hide all <img> elements before making a screenshot.
let mask_locator = page.locator("//img")
await page.screenshot({path: 'masked.png', mask: [mask_locator]})