Rayrun

How do I use the `toHaveScreenshot` method in Playwright to verify images by file name?

Answer

Sure, you can verify which image has loaded by file name using Playwright's toHaveScreenshot method. Here's how you do it:

First, import test and expect from @playwright/test:

import { test, expect } from '@playwright/test';

Then, navigate to a webpage and use expect(page).toHaveScreenshot to check if the screenshot captured by Playwright matches the expected screenshot:

test('example test', async ({ page }) => {
  await page.goto('https://ray.run');
  await expect(page).toHaveScreenshot('landing.png');
});

If there's any difference between the expected and actual screenshots, an assertion error will be thrown. Keep in mind that screenshots may vary between browsers and platforms due to differences in rendering, fonts, etc.

To update reference screenshots, run your tests with the --update-snapshots flag:

npx playwright test --update-snapshots

This command will update all reference snapshots based on your current test runs.

You can also modify how pixel differences are handled during screenshot comparison by passing options to toHaveScreenshot:

await expect(page).toHaveScreenshot({ maxDiffPixels: 100 });

This allows for a maximum of 100 differing pixels between the expected and actual screenshots before considering them as a mismatch.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

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 luc@ray.run.