hm9
hm9

Reputation: 47

Take a screenshot and compare it with another image using playwright.net - C#

I m trying to take a screenshot of a section on the page and compare it with another image already saved using playwright and .NET. I managed to take the screenshot but i cant do the comparison. On playwright site, they show how to do it using javascript but there is no equivalent in .Net. can anyone please advise how to make the code below works in .NET. Thank you

expect(await.Locator(".layer").ScreenshotAsync.toMatchSnapshot('home.png', { threshold: 0.2 });

Upvotes: 2

Views: 1576

Answers (1)

James Coliz
James Coliz

Reputation: 80

You can use ImageSharpCompare for this.

Here's how I do it. This is using MSTest, so replace Assert.IsEqual with whatever your runner uses.

  <ItemGroup>
    <PackageReference Include="Codeuctivity.ImageSharpCompare" Version="2.0.25" />
    <PackageReference Include="SixLabors.ImageSharp" Version="2.1.0" />
  </ItemGroup>
using Codeuctivity.ImageSharpCompare;
using SixLabors.ImageSharp;

var bytes = await Page.ScreenshotAsync();
using var actual = Image.Load(bytes);
using var expected = Image.Load(expected_filename);
Assert.IsTrue(ImageSharpCompare.ImagesAreEqual(actual,expected),expected_filename);

ImageSharpCompare also has options for reducing how precisely equal the images need to be in order to pass.

Upvotes: 3

Related Questions