Rayrun
← Back to Discord Forum

Can you Assert a locator by image name?

arleneandrewsposted in #help-playwright
Open in Discord
arleneandrews
arleneandrews

I have a page that has an image - is there a way to verify which image has loaded by file name?

This thread is trying to answer question "Is there a way to verify which image has loaded by file name?"

3 replies
ravikiran0186
ravikiran0186

const locator = page.locator('input'); await expect(locator).toHaveAttribute('type', 'text');

Do you only want to know which images have been loaded by filename? One way to do that would be to intercept requests by type https://playwright.dev/dotnet/docs/network#network-events

If you have a locator for the image, you could try reading (and possibly parsing) its attribute(s) with GetAttributeAsync. Say you have <img alt="playwright logo" src="/img/playwright-logo.svg" width="100" /> - locate this element, then get the src-attribute. https://playwright.dev/dotnet/docs/api/class-locator#locator-get-attribute await imageLocator.GetAttributeAsync('src')

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.

Related Discord Threads

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.