Snapshot testing in Playwright is a breeze with the SnapshotAssertions
class. This class allows you to compare screenshots of your page or elements with expected values stored in files.
Here's how you do it:
expect(await page.screenshot()).toMatchSnapshot('landing-page.png');
You can also customize the snapshot comparison. For example, you can set maxDiffPixels
to allow no more than 27 different pixels:
expect(await page.screenshot()).toMatchSnapshot('landing-page.png', { maxDiffPixels: 27 });
You can also configure the image matching threshold by setting threshold
to an acceptable perceived color difference in the YIQ color space between the same pixel in compared images (between zero and one). The default is configurable with TestConfig.expect
and defaults to 0.2.
If you want to structure your snapshot files, you can pass file path segments using an array of strings:
expect(await page.screenshot()).toMatchSnapshot(['landing', 'step2.png']);
expect(await page.screenshot()).toMatchSnapshot(['landing', 'step3.png']);
Remember, snapshot matching only works with the Playwright test runner. So, if you're not using this runner, this feature won't be available.
With the SnapshotAssertions
class, you can easily write snapshot tests and customize image comparison thresholds and naming conventions for your snapshots files. Happy testing with Playwright!
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].