In Playwright v1.41.0 the new option stylePath was added for the toHaveScreenshot() method to apply a custom stylesheet while making the screenshot.
Now you can apply a custom stylesheet (.CSS file) to your page while taking screenshots. This allows filtering out dynamic or volatile elements, hence improving the screenshot determinism.
In this lesson we will use the Facebook stories section which we had already tested in one of the previous lessons.
Let’s imagine we want to test the layout, so we don’t actually need the dynamic parts such as pictures inside the story’s containers as well as the usernames. And of course, we don’t want to see the fresh-baked venison photo in my own story 😆.
So, the first thing we have to do is create a new stylesheet file in our test project, let’s say src/styles/style.css.
In style.css, we can define the new styles that will be applied during the screenshot assertion. In our case, I think we could hide the images, story usernames, and some other elements in the “What’s on your mind?” section.
[aria-label="Stories"] img,
[aria-label="Stories"] span,
[aria-label="Create a post"] img,
[aria-label="Create a post"] span {
visibility: hidden;
}
Now you can add the path to style.css in your screenshot assertion method:
test('Playwright CSS test', async ({page}) => {
await page.goto('https://facebook.com');
await expect(page).toHaveScreenshot('facebook', { stylePath: `${__dirname}/../styles/style.css` });
});
Now the screenshot method is filtering out our dynamic elements from the screenshot file.
It seems like a pretty simple and accurate approach to asserting the screenshots in visual testing of pages with dynamic elements.
You can still hide the element using the page.evaluate()
method by executing JavaScript in the browser’s console as well as using the element masking. Check out the ‘How to Mask Dynamic Elements in Automated Visual Tests’ guide.