Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.ScreenshotHelper
ElementHandleScreenshotTests.cs
Source:ElementHandleScreenshotTests.cs
...40 await Page.GotoAsync(Server.Prefix + "/grid.html");41 await Page.EvaluateAsync("window.scrollBy(50, 100)");42 var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(3)");43 byte[] screenshot = await elementHandle.ScreenshotAsync();44 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", screenshot));45 }46 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take into account padding and border")]47 public async Task ShouldTakeIntoAccountPaddingAndBorder()48 {49 await Page.SetViewportSizeAsync(500, 500);50 await Page.SetContentAsync(@"51 <div style=""height: 14px"">oooo</div>52 <style>div {53 border: 2px solid blue;54 background: green;55 width: 50px;56 height: 50px;57 }58 </style>59 <div id=""d""></div>");60 var elementHandle = await Page.QuerySelectorAsync("div#d");61 byte[] screenshot = await elementHandle.ScreenshotAsync();62 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-padding-border.png", screenshot));63 }64 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should capture full element when larger than viewport in parallel")]65 public async Task ShouldCaptureFullElementWhenLargerThanViewportInParallel()66 {67 await Page.SetViewportSizeAsync(500, 500);68 await Page.SetContentAsync(@"69 <div style=""height: 14px"">oooo</div>70 <style>71 div.to-screenshot {72 border: 1px solid blue;73 width: 600px;74 height: 600px;75 margin-left: 50px;76 }77 ::-webkit-scrollbar{78 display: none;79 }80 </style>81 <div class=""to-screenshot""></div>82 <div class=""to-screenshot""></div>83 <div class=""to-screenshot""></div>84 ");85 var elementHandles = await Page.QuerySelectorAllAsync("div.to-screenshot");86 var screenshotTasks = elementHandles.Select(e => e.ScreenshotAsync()).ToArray();87 await TaskUtils.WhenAll(screenshotTasks);88 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-larger-than-viewport.png", screenshotTasks.ElementAt(2).Result));89 }90 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should capture full element when larger than viewport")]91 public async Task ShouldCaptureFullElementWhenLargerThanViewport()92 {93 await Page.SetViewportSizeAsync(500, 500);94 await Page.SetContentAsync(@"95 <div style=""height: 14px"">oooo</div>96 <style>97 div.to-screenshot {98 border: 1px solid blue;99 width: 600px;100 height: 600px;101 margin-left: 50px;102 }103 ::-webkit-scrollbar{104 display: none;105 }106 </style>107 <div class=""to-screenshot""></div>108 <div class=""to-screenshot""></div>109 <div class=""to-screenshot""></div>");110 var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot");111 byte[] screenshot = await elementHandle.ScreenshotAsync();112 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-larger-than-viewport.png", screenshot));113 await TestUtils.VerifyViewportAsync(Page, 500, 500);114 }115 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should scroll element into view")]116 public async Task ShouldScrollElementIntoView()117 {118 await Page.SetViewportSizeAsync(500, 500);119 await Page.SetContentAsync(@"120 <div style=""height: 14px"">oooo</div>121 <style>div.above {122 border: 2px solid blue;123 background: red;124 height: 1500px;125 }126 div.to-screenshot {127 border: 2px solid blue;128 background: green;129 width: 50px;130 height: 50px;131 }132 </style>133 <div class=""above""></div>134 <div class=""to-screenshot""></div>");135 var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot");136 byte[] screenshot = await elementHandle.ScreenshotAsync();137 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-scrolled-into-view.png", screenshot));138 }139 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should scroll 15000px into view")]140 public async Task ShouldScroll15000pxIntoView()141 {142 await Page.SetViewportSizeAsync(500, 500);143 await Page.SetContentAsync(@"144 <div style=""height: 14px"">oooo</div>145 <style>div.above {146 border: 2px solid blue;147 background: red;148 height: 15000px;149 }150 div.to-screenshot {151 border: 2px solid blue;152 background: green;153 width: 50px;154 height: 50px;155 }156 </style>157 <div class=""above""></div>158 <div class=""to-screenshot""></div>");159 var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot");160 byte[] screenshot = await elementHandle.ScreenshotAsync();161 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-scrolled-into-view.png", screenshot));162 }163 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with a rotated element")]164 public async Task ShouldWorkWithARotatedElement()165 {166 await Page.SetViewportSizeAsync(500, 500);167 await Page.SetContentAsync(@"168 <div style='position: absolute;169 top: 100px;170 left: 100px;171 width: 100px;172 height: 100px;173 background: green;174 transform: rotateZ(200deg); '> </div>175 ");176 var elementHandle = await Page.QuerySelectorAsync("div");177 byte[] screenshot = await elementHandle.ScreenshotAsync();178 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-rotate.png", screenshot));179 }180 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should fail to screenshot a detached element")]181 public async Task ShouldFailToScreenshotADetachedElement()182 {183 await Page.SetContentAsync("<h1>remove this</h1>");184 var elementHandle = await Page.QuerySelectorAsync("h1");185 await Page.EvaluateAsync("element => element.remove()", elementHandle);186 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => elementHandle.ScreenshotAsync());187 StringAssert.Contains("Element is not attached to the DOM", exception.Message);188 }189 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should timeout waiting for visible")]190 public async Task ShouldTimeoutWaitingForVisible()191 {192 await Page.SetContentAsync(@"<div style='width: 50px; height: 0'></div>");193 var elementHandle = await Page.QuerySelectorAsync("div");194 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => elementHandle.ScreenshotAsync(new() { Timeout = 3000 }));195 StringAssert.Contains("Timeout 3000ms exceeded", exception.Message);196 StringAssert.Contains("element is not visible", exception.Message);197 }198 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should wait for visible")]199 public async Task ShouldWaitForVisible()200 {201 await Page.SetViewportSizeAsync(500, 500);202 await Page.GotoAsync(Server.Prefix + "/grid.html");203 await Page.EvaluateAsync("() => window.scrollBy(50, 100)");204 var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(3)");205 await elementHandle.EvaluateAsync("e => e.style.visibility = 'hidden'");206 var task = elementHandle.ScreenshotAsync();207 for (int i = 0; i < 10; i++)208 {209 await Page.EvaluateAsync("() => new Promise(f => requestAnimationFrame(f))");210 }211 Assert.False(task.IsCompleted);212 await elementHandle.EvaluateAsync("e => e.style.visibility = 'visible'");213 byte[] screenshot = await task;214 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", screenshot));215 }216 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work for an element with fractional dimensions")]217 public async Task ShouldWorkForAnElementWithFractionalDimensions()218 {219 await Page.SetContentAsync("<div style=\"width:48.51px;height:19.8px;border:1px solid black;\"></div>");220 var elementHandle = await Page.QuerySelectorAsync("div");221 byte[] screenshot = await elementHandle.ScreenshotAsync();222 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-fractional.png", screenshot));223 }224 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with a mobile viewport")]225 [Skip(SkipAttribute.Targets.Firefox)]226 public async Task ShouldWorkWithAMobileViewport()227 {228 await using var context = await Browser.NewContextAsync(new()229 {230 ViewportSize = new()231 {232 Width = 320,233 Height = 480,234 },235 IsMobile = true,236 });237 var page = await context.NewPageAsync();238 await page.GotoAsync(Server.Prefix + "/grid.html");239 await page.EvaluateAsync("() => window.scrollBy(50, 100)");240 var elementHandle = await page.QuerySelectorAsync(".box:nth-of-type(3)");241 byte[] screenshot = await elementHandle.ScreenshotAsync();242 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-mobile.png", screenshot));243 }244 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with device scale factor")]245 [Skip(SkipAttribute.Targets.Firefox)]246 public async Task ShouldWorkWithDeviceScaleFactor()247 {248 await using var context = await Browser.NewContextAsync(new()249 {250 ViewportSize = new()251 {252 Width = 320,253 Height = 480,254 },255 DeviceScaleFactor = 2,256 });257 var page = await context.NewPageAsync();258 await page.GotoAsync(Server.Prefix + "/grid.html");259 await page.EvaluateAsync("() => window.scrollBy(50, 100)");260 var elementHandle = await page.QuerySelectorAsync(".box:nth-of-type(3)");261 byte[] screenshot = await elementHandle.ScreenshotAsync();262 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-mobile-dsf.png", screenshot));263 }264 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work for an element with an offset")]265 public async Task ShouldWorkForAnElementWithAnOffset()266 {267 await Page.SetContentAsync("<div style=\"position:absolute; top: 10.3px; left: 20.4px;width:50.3px;height:20.2px;border:1px solid black;\"></div>");268 var elementHandle = await Page.QuerySelectorAsync("div");269 byte[] screenshot = await elementHandle.ScreenshotAsync();270 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-fractional-offset.png", screenshot));271 }272 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take screenshots when default viewport is null")]273 public async Task ShouldTakeScreenshotsWhenDefaultViewportIsNull()274 {275 await using var context = await Browser.NewContextAsync(new()276 {277 ViewportSize = ViewportSize.NoViewport278 });279 var page = await context.NewPageAsync();280 await page.SetContentAsync("<div style='height: 10000px; background: red'></div>");281 var windowSize = await page.EvaluateAsync<ViewportSize>("() => ({ width: window.innerWidth * window.devicePixelRatio, height: window.innerHeight * window.devicePixelRatio })");282 var sizeBefore = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");283 byte[] screenshot = await page.ScreenshotAsync();284 Assert.NotNull(screenshot);285 var decoded = Image.Load(screenshot);286 Assert.AreEqual(windowSize.Width, decoded.Width);287 Assert.AreEqual(windowSize.Height, decoded.Height);288 var sizeAfter = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");289 Assert.AreEqual(sizeBefore.Width, sizeAfter.Width);290 Assert.AreEqual(sizeBefore.Height, sizeAfter.Height);291 }292 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take fullPage screenshots when default viewport is null")]293 public async Task ShouldTakeFullPageScreenshotsWhenDefaultViewportIsNull()294 {295 await using var context = await Browser.NewContextAsync(new()296 {297 ViewportSize = ViewportSize.NoViewport298 });299 var page = await context.NewPageAsync();300 await page.GotoAsync(Server.Prefix + "/grid.html");301 var sizeBefore = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");302 byte[] screenshot = await page.ScreenshotAsync(new() { FullPage = true });303 Assert.NotNull(screenshot);304 var sizeAfter = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");305 Assert.AreEqual(sizeBefore.Width, sizeAfter.Width);306 Assert.AreEqual(sizeBefore.Height, sizeAfter.Height);307 }308 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should restore default viewport after fullPage screenshot")]309 public async Task ShouldRestoreDefaultViewportAfterFullPageScreenshot()310 {311 await using var context = await Browser.NewContextAsync(new()312 {313 ViewportSize = new() { Width = 456, Height = 789 },314 });315 var page = await context.NewPageAsync();316 await TestUtils.VerifyViewportAsync(page, 456, 789);317 byte[] screenshot = await page.ScreenshotAsync(new() { FullPage = true });318 Assert.NotNull(screenshot);319 await TestUtils.VerifyViewportAsync(page, 456, 789);320 }321 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take element screenshot when default viewport is null and restore back")]322 public async Task ShouldTakeElementScreenshotWhenDefaultViewportIsNullAndRestoreBack()323 {324 await using var context = await Browser.NewContextAsync(new()325 {326 ViewportSize = ViewportSize.NoViewport,327 });328 var page = await context.NewPageAsync();329 await page.SetContentAsync(@"330 <div style=""height: 14px"">oooo</div>331 <style>332 div.to-screenshot {333 border: 1px solid blue;334 width: 600px;335 height: 600px;336 margin-left: 50px;337 }338 ::-webkit-scrollbar{339 display: none;340 }341 </style>342 <div class=""to-screenshot""></div>343 <div class=""to-screenshot""></div>344 <div class=""to-screenshot""></div>");345 var sizeBefore = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");346 var elementHandle = await page.QuerySelectorAsync("div.to-screenshot");347 byte[] screenshot = await elementHandle.ScreenshotAsync();348 Assert.NotNull(screenshot);349 var sizeAfter = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");350 Assert.AreEqual(sizeBefore.Width, sizeAfter.Width);351 Assert.AreEqual(sizeBefore.Height, sizeAfter.Height);352 }353 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take screenshot of disabled button")]354 public async Task ShouldTakeScreenshotOfDisabledButton()355 {356 await Page.SetViewportSizeAsync(500, 500);357 await Page.SetContentAsync("<button disabled>Click me</button>");358 var button = await Page.QuerySelectorAsync("button");359 byte[] screenshot = await button.ScreenshotAsync();360 Assert.NotNull(screenshot);361 }362 [PlaywrightTest("elementhandle-screenshot.spec.ts", "path option should create subdirectories")]363 public async Task PathOptionShouldCreateSubdirectories()364 {365 await Page.SetViewportSizeAsync(500, 500);366 await Page.GotoAsync(Server.Prefix + "/grid.html");367 await Page.EvaluateAsync("() => window.scrollBy(50, 100)");368 var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(3)");369 using var tmpDir = new TempDirectory();370 string outputPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "screenshot.png");371 await elementHandle.ScreenshotAsync(new() { Path = outputPath });372 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", outputPath));373 }374 }375}...
PageScreenshotTests.cs
Source:PageScreenshotTests.cs
...38 {39 await Page.SetViewportSizeAsync(500, 500);40 await Page.GotoAsync(Server.Prefix + "/grid.html");41 byte[] screenshot = await Page.ScreenshotAsync();42 Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", screenshot));43 }44 [PlaywrightTest("page-screenshot.spec.ts", "should clip rect")]45 public async Task ShouldClipRect()46 {47 await Page.SetViewportSizeAsync(500, 500);48 await Page.GotoAsync(Server.Prefix + "/grid.html");49 byte[] screenshot = await Page.ScreenshotAsync(new()50 {51 Clip = new()52 {53 X = 50,54 Y = 100,55 Width = 150,56 Height = 10057 }58 }59 );60 Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot));61 }62 [PlaywrightTest("page-screenshot.spec.ts", "should clip rect with fullPage")]63 public async Task ShouldClipRectWithFullPage()64 {65 await Page.SetViewportSizeAsync(500, 500);66 await Page.GotoAsync(Server.Prefix + "/grid.html");67 await Page.EvaluateAsync("() => window.scrollBy(150, 200)");68 byte[] screenshot = await Page.ScreenshotAsync(new()69 {70 FullPage = true,71 Clip = new()72 {73 X = 50,74 Y = 100,75 Width = 150,76 Height = 100,77 }78 });79 Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot));80 }81 [PlaywrightTest("page-screenshot.spec.ts", "should clip elements to the viewport")]82 public async Task ShouldClipElementsToTheViewport()83 {84 await Page.SetViewportSizeAsync(500, 500);85 await Page.GotoAsync(Server.Prefix + "/grid.html");86 byte[] screenshot = await Page.ScreenshotAsync(new()87 {88 Clip = new()89 {90 X = 50,91 Y = 450,92 Width = 1000,93 Height = 100,94 }95 });96 Assert.True(ScreenshotHelper.PixelMatch("screenshot-offscreen-clip.png", screenshot));97 }98 [PlaywrightTest("page-screenshot.spec.ts", "should throw on clip outside the viewport")]99 public async Task ShouldThrowOnClipOutsideTheViewport()100 {101 await Page.SetViewportSizeAsync(500, 500);102 await Page.GotoAsync(Server.Prefix + "/grid.html");103 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.ScreenshotAsync(new()104 {105 Clip = new()106 {107 X = 50,108 Y = 650,109 Width = 100,110 Height = 100,111 }112 }));113 StringAssert.Contains("Clipped area is either empty or outside the resulting image", exception.Message);114 }115 [PlaywrightTest("page-screenshot.spec.ts", "should run in parallel")]116 public async Task ShouldRunInParallel()117 {118 await Page.SetViewportSizeAsync(500, 500);119 await Page.GotoAsync(Server.Prefix + "/grid.html");120 var tasks = new List<Task<byte[]>>();121 for (int i = 0; i < 3; ++i)122 {123 tasks.Add(Page.ScreenshotAsync(new()124 {125 Clip = new()126 {127 X = 50 * i,128 Y = 0,129 Width = 50,130 Height = 50131 }132 }));133 }134 await TaskUtils.WhenAll(tasks);135 Assert.True(ScreenshotHelper.PixelMatch("grid-cell-1.png", tasks[0].Result));136 }137 [PlaywrightTest("page-screenshot.spec.ts", "should take fullPage screenshots")]138 public async Task ShouldTakeFullPageScreenshots()139 {140 await Page.SetViewportSizeAsync(500, 500);141 await Page.GotoAsync(Server.Prefix + "/grid.html");142 byte[] screenshot = await Page.ScreenshotAsync(new() { FullPage = true });143 Assert.True(ScreenshotHelper.PixelMatch("screenshot-grid-fullpage.png", screenshot));144 }145 [PlaywrightTest("page-screenshot.spec.ts", "should restore viewport after fullPage screenshot")]146 public async Task ShouldRestoreViewportAfterFullPageScreenshot()147 {148 await Page.SetViewportSizeAsync(500, 500);149 await Page.GotoAsync(Server.Prefix + "/grid.html");150 await Page.ScreenshotAsync(new() { FullPage = true });151 Assert.AreEqual(500, Page.ViewportSize.Width);152 Assert.AreEqual(500, Page.ViewportSize.Height);153 }154 [PlaywrightTest("page-screenshot.spec.ts", "should run in parallel in multiple pages")]155 public async Task ShouldRunInParallelInMultiplePages()156 {157 int n = 5;158 var pageTasks = new List<Task<IPage>>();159 for (int i = 0; i < n; i++)160 {161 async Task<IPage> Func()162 {163 var page = await Context.NewPageAsync();164 await page.GotoAsync(Server.Prefix + "/grid.html");165 return page;166 }167 pageTasks.Add(Func());168 }169 await TaskUtils.WhenAll(pageTasks);170 var screenshotTasks = new List<Task<byte[]>>();171 for (int i = 0; i < n; i++)172 {173 screenshotTasks.Add(pageTasks[i].Result.ScreenshotAsync(new()174 {175 Clip = new()176 {177 X = 50 * (i % 2),178 Y = 0,179 Width = 50,180 Height = 50181 }182 }));183 }184 await TaskUtils.WhenAll(screenshotTasks);185 for (int i = 0; i < n; i++)186 {187 Assert.True(ScreenshotHelper.PixelMatch($"grid-cell-{i % 2}.png", screenshotTasks[i].Result));188 }189 var closeTasks = new List<Task>();190 for (int i = 0; i < n; i++)191 {192 closeTasks.Add(pageTasks[i].Result.CloseAsync());193 }194 await TaskUtils.WhenAll(closeTasks);195 }196 [PlaywrightTest("page-screenshot.spec.ts", "should allow transparency")]197 [Skip(SkipAttribute.Targets.Firefox)]198 public async Task ShouldAllowTransparency()199 {200 await Page.SetViewportSizeAsync(50, 150);201 await Page.GotoAsync(Server.EmptyPage);202 byte[] screenshot = await Page.ScreenshotAsync(new() { OmitBackground = true });203 Assert.True(ScreenshotHelper.PixelMatch("transparent.png", screenshot));204 }205 [PlaywrightTest("page-screenshot.spec.ts", "should render white background on jpeg file")]206 public async Task ShouldRenderWhiteBackgroundOnJpegFile()207 {208 await Page.SetViewportSizeAsync(100, 100);209 await Page.GotoAsync(Server.EmptyPage);210 byte[] screenshot = await Page.ScreenshotAsync(new()211 {212 OmitBackground = true,213 Type = ScreenshotType.Jpeg,214 });215 Assert.True(ScreenshotHelper.PixelMatch("white.jpg", screenshot));216 }217 [PlaywrightTest("page-screenshot.spec.ts", "should work with odd clip size on Retina displays")]218 public async Task ShouldWorkWithOddClipSizeOnRetinaDisplays()219 {220 byte[] screenshot = await Page.ScreenshotAsync(new()221 {222 Clip = new()223 {224 X = 0,225 Y = 0,226 Width = 11,227 Height = 11228 }229 });230 Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-odd-size.png", screenshot));231 }232 [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport")]233 [Skip(SkipAttribute.Targets.Firefox)]234 public async Task ShouldWorkWithAMobileViewport()235 {236 await using var context = await Browser.NewContextAsync(new()237 {238 ViewportSize = new()239 {240 Width = 320,241 Height = 480,242 },243 IsMobile = true,244 });245 var page = await context.NewPageAsync();246 await page.GotoAsync(Server.Prefix + "/overflow.html");247 byte[] screenshot = await page.ScreenshotAsync();248 Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile.png", screenshot));249 }250 [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport and clip")]251 [Skip(SkipAttribute.Targets.Firefox)]252 public async Task ShouldWorkWithAMobileViewportAndClip()253 {254 await using var context = await Browser.NewContextAsync(new()255 {256 ViewportSize = new()257 {258 Width = 320,259 Height = 480,260 },261 IsMobile = true,262 });263 var page = await context.NewPageAsync();264 await page.GotoAsync(Server.Prefix + "/overflow.html");265 byte[] screenshot = await page.ScreenshotAsync(new()266 {267 Clip = new()268 {269 X = 10,270 Y = 10,271 Width = 100,272 Height = 150273 }274 });275 Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile-clip.png", screenshot));276 }277 [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport and fullPage")]278 [Skip(SkipAttribute.Targets.Firefox)]279 public async Task ShouldWorkWithAMobileViewportAndFullPage()280 {281 await using var context = await Browser.NewContextAsync(new()282 {283 ViewportSize = new()284 {285 Width = 320,286 Height = 480,287 },288 IsMobile = true,289 });290 var page = await context.NewPageAsync();291 await page.GotoAsync(Server.Prefix + "/overflow-large.html");292 byte[] screenshot = await page.ScreenshotAsync(new() { FullPage = true });293 Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile-fullpage.png", screenshot));294 }295 [PlaywrightTest("page-screenshot.spec.ts", "should work for canvas")]296 public async Task ShouldWorkForCanvas()297 {298 await Page.SetViewportSizeAsync(500, 500);299 await Page.GotoAsync(Server.Prefix + "/screenshots/canvas.html");300 byte[] screenshot = await Page.ScreenshotAsync();301 Assert.True(ScreenshotHelper.PixelMatch("screenshot-canvas.png", screenshot));302 }303 [PlaywrightTest("page-screenshot.spec.ts", "should work for webgl")]304 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]305 public async Task ShouldWorkForWebgl()306 {307 await Page.SetViewportSizeAsync(640, 480);308 await Page.GotoAsync(Server.Prefix + "/screenshots/webgl.html");309 byte[] screenshot = await Page.ScreenshotAsync();310 Assert.True(ScreenshotHelper.PixelMatch("screenshot-webgl.png", screenshot));311 }312 [PlaywrightTest("page-screenshot.spec.ts", "should work for translateZ")]313 public async Task ShouldWorkForTranslateZ()314 {315 await Page.SetViewportSizeAsync(500, 500);316 await Page.GotoAsync(Server.Prefix + "/screenshots/translateZ.html");317 byte[] screenshot = await Page.ScreenshotAsync();318 Assert.True(ScreenshotHelper.PixelMatch("screenshot-translateZ.png", screenshot));319 }320 [PlaywrightTest("page-screenshot.spec.ts", "should work while navigating")]321 public async Task ShouldWorkWhileNavigating()322 {323 await Page.SetViewportSizeAsync(500, 500);324 await Page.GotoAsync(Server.Prefix + "/redirectloop1.html");325 for (int i = 0; i < 10; ++i)326 {327 try328 {329 await Page.ScreenshotAsync();330 }331 catch (Exception ex) when (ex.Message.Contains("Cannot take a screenshot while page is navigating"))332 {333 }334 }335 }336 [PlaywrightTest("page-screenshot.spec.ts", "should work with device scale factor")]337 public async Task ShouldWorkWithDeviceScaleFactor()338 {339 await using var context = await Browser.NewContextAsync(new()340 {341 ViewportSize = new()342 {343 Width = 320,344 Height = 480,345 },346 DeviceScaleFactor = 2,347 });348 var page = await context.NewPageAsync();349 await page.GotoAsync(Server.Prefix + "/grid.html");350 byte[] screenshot = await page.ScreenshotAsync();351 Assert.True(ScreenshotHelper.PixelMatch("screenshot-device-scale-factor.png", screenshot));352 }353 [PlaywrightTest("page-screenshot.spec.ts", "should work with iframe in shadow")]354 public async Task ShouldWorkWithiFrameInShadow()355 {356 await using var context = await Browser.NewContextAsync(new()357 {358 ViewportSize = new()359 {360 Width = 500,361 Height = 500,362 },363 });364 var page = await context.NewPageAsync();365 await page.GotoAsync(Server.Prefix + "/grid-iframe-in-shadow.html");366 byte[] screenshot = await page.ScreenshotAsync();367 Assert.True(ScreenshotHelper.PixelMatch("screenshot-iframe.png", screenshot));368 }369 [PlaywrightTest("page-screenshot.spec.ts", "path option should work")]370 public async Task PathOptionShouldWork()371 {372 await Page.SetViewportSizeAsync(500, 500);373 await Page.GotoAsync(Server.Prefix + "/grid.html");374 using var tmpDir = new TempDirectory();375 string outputPath = Path.Combine(tmpDir.Path, "screenshot.png");376 await Page.ScreenshotAsync(new() { Path = outputPath });377 Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", outputPath));378 }379 [PlaywrightTest("page-screenshot.spec.ts", "path option should create subdirectories")]380 public async Task PathOptionShouldCreateSubdirectories()381 {382 await Page.SetViewportSizeAsync(500, 500);383 await Page.GotoAsync(Server.Prefix + "/grid.html");384 using var tmpDir = new TempDirectory();385 string outputPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "screenshot.png");386 await Page.ScreenshotAsync(new() { Path = outputPath });387 Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", outputPath));388 }389 [PlaywrightTest("page-screenshot.spec.ts", "path option should detect joeg")]390 public async Task PathOptionShouldDetectJpeg()391 {392 await Page.SetViewportSizeAsync(100, 100);393 await Page.GotoAsync(Server.EmptyPage);394 using var tmpDir = new TempDirectory();395 string outputPath = Path.Combine(tmpDir.Path, "screenshot.jpg");396 await Page.ScreenshotAsync(new() { Path = outputPath, OmitBackground = true });397 Assert.True(ScreenshotHelper.PixelMatch("white.jpg", outputPath));398 }399 [PlaywrightTest("page-screenshot.spec.ts", "path option should throw for unsupported mime type")]400 public async Task PathOptionShouldThrowForUnsupportedMimeType()401 {402 var exception = await PlaywrightAssert.ThrowsAsync<ArgumentException>(() => Page.ScreenshotAsync(new() { Path = "file.txt" }));403 StringAssert.Contains("path: unsupported mime type \"text/plain\"", exception.Message);404 }405 }406}...
PageRequestFulfillTests.cs
Source:PageRequestFulfillTests.cs
...91 document.body.appendChild(img);92 return new Promise(fulfill => img.onload = fulfill);93 }", Server.Prefix);94 var img = await Page.QuerySelectorAsync("img");95 Assert.True(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotAsync()));96 }97 [PlaywrightTest("page-request-fulfill.spec.ts", "should allow mocking svg with charset")]98 [Ignore("We need screenshots for this")]99 public void ShouldAllowMockingSvgWithCharset()100 {101 }102 [PlaywrightTest("page-request-fulfill.spec.ts", "should work with file path")]103 [Ignore("We need screenshots for this")]104 public async Task ShouldWorkWithFilePath()105 {106 await Page.RouteAsync("**/*", (route) =>107 {108 route.FulfillAsync(new()109 {110 ContentType = "shouldBeIgnored",111 Path = TestUtils.GetAsset("pptr.png"),112 });113 });114 await Page.EvaluateAsync(@"PREFIX => {115 const img = document.createElement('img');116 img.src = PREFIX + '/does-not-exist.png';117 document.body.appendChild(img);118 return new Promise(fulfill => img.onload = fulfill);119 }", Server.Prefix);120 var img = await Page.QuerySelectorAsync("img");121 Assert.True(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotAsync()));122 }123 [PlaywrightTest("page-request-fulfill.spec.ts", "should stringify intercepted request response headers")]124 public async Task ShouldStringifyInterceptedRequestResponseHeaders()125 {126 await Page.RouteAsync("**/*", (route) =>127 {128 route.FulfillAsync(new()129 {130 Status = (int)HttpStatusCode.OK,131 Headers = new Dictionary<string, string>132 {133 ["foo"] = "true"134 },135 Body = "Yo, page!",...
ScreenshotHelper.cs
Source:ScreenshotHelper.cs
...26using SixLabors.ImageSharp;27using SixLabors.ImageSharp.PixelFormats;28namespace Microsoft.Playwright.Tests29{30 internal class ScreenshotHelper31 {32 internal static bool PixelMatch(string screenShotFile, string fileName)33 => PixelMatch(screenShotFile, File.ReadAllBytes(fileName));34 internal static bool PixelMatch(string screenShotFile, byte[] screenshot)35 {36 const int pixelThreshold = 10;37 const decimal totalTolerance = 0.05m;38 var baseImage = Image.Load<Rgb24>(Path.Combine(TestUtils.FindParentDirectory("Screenshots"), TestConstants.BrowserName, screenShotFile));39 var compareImage = Image.Load<Rgb24>(screenshot);40 //Just for debugging purpose41 compareImage.Save(Path.Combine(TestUtils.FindParentDirectory("Screenshots"), TestConstants.BrowserName, "test.png"));42 if (baseImage.Width != compareImage.Width || baseImage.Height != compareImage.Height)43 {44 return false;...
ScreenshotHelper
Using AI Code Generation
1using Microsoft.Playwright.Tests;2using System;3{4 {5 static void Main(string[] args)6 {7 ScreenshotHelper screenshotHelper = new ScreenshotHelper();8 screenshotHelper.TakeScreenshot();9 }10 }11}12using Microsoft.Playwright;13using System;14using System.Collections.Generic;15using System.Text;16using System.Threading.Tasks;17{18 {19 public async Task TakeScreenshot()20 {21 var playwright = await Playwright.CreateAsync();22 var browser = await playwright.Chromium.LaunchAsync();23 var page = await browser.NewPageAsync();24 await page.ScreenshotAsync("google.png");25 await browser.CloseAsync();26 }27 }28}29using Microsoft.Playwright;30using System;31using System.Collections.Generic;32using System.Text;33using System.Threading.Tasks;34{35 {36 public async Task TakeScreenshot()37 {38 var playwright = await Playwright.CreateAsync();39 var browser = await playwright.Chromium.LaunchAsync();40 var page = await browser.NewPageAsync();41 await page.ScreenshotAsync("google.png");42 await browser.CloseAsync();43 }44 }45}
ScreenshotHelper
Using AI Code Generation
1ScreenshotHelper screenshotHelper = new ScreenshotHelper();2screenshotHelper.TakeScreenshot(page, "2.png");3ScreenshotHelper screenshotHelper = new ScreenshotHelper();4screenshotHelper.TakeScreenshot(page, "3.png");5ScreenshotHelper screenshotHelper = new ScreenshotHelper();6screenshotHelper.TakeScreenshot(page, "4.png");7ScreenshotHelper screenshotHelper = new ScreenshotHelper();8screenshotHelper.TakeScreenshot(page, "5.png");9ScreenshotHelper screenshotHelper = new ScreenshotHelper();10screenshotHelper.TakeScreenshot(page, "6.png");11ScreenshotHelper screenshotHelper = new ScreenshotHelper();12screenshotHelper.TakeScreenshot(page, "7.png");13ScreenshotHelper screenshotHelper = new ScreenshotHelper();14screenshotHelper.TakeScreenshot(page, "8.png");15ScreenshotHelper screenshotHelper = new ScreenshotHelper();16screenshotHelper.TakeScreenshot(page, "9.png");17ScreenshotHelper screenshotHelper = new ScreenshotHelper();18screenshotHelper.TakeScreenshot(page, "10.png");19ScreenshotHelper screenshotHelper = new ScreenshotHelper();20screenshotHelper.TakeScreenshot(page, "11.png");21ScreenshotHelper screenshotHelper = new ScreenshotHelper();22screenshotHelper.TakeScreenshot(page, "12.png");23ScreenshotHelper screenshotHelper = new ScreenshotHelper();24screenshotHelper.TakeScreenshot(page, "13.png");
ScreenshotHelper
Using AI Code Generation
1using Microsoft.Playwright.Tests;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 var browser = await Playwright.CreateAsync().Chromium.LaunchAsync();9 var page = await browser.NewPageAsync();10 await page.ScreenshotAsync("google.png");11 await browser.CloseAsync();12 }13 }14}15Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "2", "2.csproj", "{7D9F2C3F-1E0D-4B6F-8B0E-6B2B6C4C4B4B}"16 GlobalSection(SolutionConfigurationPlatforms) = preSolution17 GlobalSection(ProjectConfigurationPlatforms) = postSolution18 {7D9F2C3F-1E0D-4B6F-8B0E-6B2B6C4C4B4B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU19 {7D9F2C3F-1E0D-4B6F-8B0E-6B2B6C4C4B4B}.Debug|Any CPU.Build.0 = Debug|Any CPU20 {7D9
ScreenshotHelper
Using AI Code Generation
1using Microsoft.Playwright.Tests;2ScreenshotHelper screenshotHelper = new ScreenshotHelper();3screenshotHelper.TakeScreenshot("2");4using Microsoft.Playwright.Tests;5ScreenshotHelper screenshotHelper = new ScreenshotHelper();6screenshotHelper.TakeScreenshot("3");
ScreenshotHelper
Using AI Code Generation
1using Microsoft.Playwright.Tests;2using NUnit.Framework;3using System;4using System.Collections.Generic;5using System.IO;6using System.Text;7{8 {9 public async void Test1()10 {11 using var playwright = await Playwright.CreateAsync();12 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions13 {14 Args = new[] { "--no-sandbox" }15 });16 var page = await browser.NewPageAsync();17 await page.ScreenshotAsync(new PageScreenshotOptions18 {19 });20 await browser.CloseAsync();21 }22 }23}24using Microsoft.Playwright.Tests;25using NUnit.Framework;26using System;27using System.Collections.Generic;28using System.IO;29using System.Text;30{31 {32 public async void Test1()33 {34 using var playwright = await Playwright.CreateAsync();35 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions36 {37 Args = new[] { "--no-sandbox" }38 });39 var page = await browser.NewPageAsync();40 var path = Path.Combine(Directory.GetCurrentDirectory(), "Screenshots", "test.png");41 await page.ScreenshotAsync(new PageScreenshotOptions42 {43 });44 await browser.CloseAsync();45 }46 }47}
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!