How to use ShouldWork method of Microsoft.Playwright.Tests.PageScreenshotTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageScreenshotTests.ShouldWork

Run Playwright-dotnet automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

PageScreenshotTests.cs

Source: PageScreenshotTests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) 2020 Darío Kondratiuk
5 * Modifications copyright (c) Microsoft Corporation.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 */
25
26using System;
27using System.Collections.Generic;
28using System.IO;
29using System.Threading.Tasks;
30using Microsoft.Playwright.NUnit;
31using NUnit.Framework;
32
33namespace Microsoft.Playwright.Tests
34{
35    ///<playwright-file>page-screenshot.spec.ts</playwright-file>
36
37    public class PageScreenshotTests : PageTestEx
38    {
39        [PlaywrightTest("page-screenshot.spec.ts", "should work")]
40        public async Task ShouldWork()
41        {
42            await Page.SetViewportSizeAsync(500, 500);
43            await Page.GotoAsync(Server.Prefix + "/grid.html");
44            byte[] screenshot = await Page.ScreenshotAsync();
45            Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", screenshot));
46        }
47
48        [PlaywrightTest("page-screenshot.spec.ts", "should clip rect")]
49        public async Task ShouldClipRect()
50        {
51            await Page.SetViewportSizeAsync(500, 500);
52            await Page.GotoAsync(Server.Prefix + "/grid.html");
53            byte[] screenshot = await Page.ScreenshotAsync(new()
54            {
55                Clip = new()
56                {
57                    X = 50,
58                    Y = 100,
59                    Width = 150,
60                    Height = 100
61                }
62            }
63            );
64            Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot));
65        }
66
67        [PlaywrightTest("page-screenshot.spec.ts", "should clip rect with fullPage")]
68        public async Task ShouldClipRectWithFullPage()
69        {
70            await Page.SetViewportSizeAsync(500, 500);
71            await Page.GotoAsync(Server.Prefix + "/grid.html");
72            await Page.EvaluateAsync("() => window.scrollBy(150, 200)");
73            byte[] screenshot = await Page.ScreenshotAsync(new()
74            {
75                FullPage = true,
76                Clip = new()
77                {
78                    X = 50,
79                    Y = 100,
80                    Width = 150,
81                    Height = 100,
82                }
83            });
84            Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot));
85        }
86
87        [PlaywrightTest("page-screenshot.spec.ts", "should clip elements to the viewport")]
88        public async Task ShouldClipElementsToTheViewport()
89        {
90            await Page.SetViewportSizeAsync(500, 500);
91            await Page.GotoAsync(Server.Prefix + "/grid.html");
92            byte[] screenshot = await Page.ScreenshotAsync(new()
93            {
94                Clip = new()
95                {
96                    X = 50,
97                    Y = 450,
98                    Width = 1000,
99                    Height = 100,
100                }
101            });
102            Assert.True(ScreenshotHelper.PixelMatch("screenshot-offscreen-clip.png", screenshot));
103        }
104
105        [PlaywrightTest("page-screenshot.spec.ts", "should throw on clip outside the viewport")]
106        public async Task ShouldThrowOnClipOutsideTheViewport()
107        {
108            await Page.SetViewportSizeAsync(500, 500);
109            await Page.GotoAsync(Server.Prefix + "/grid.html");
110            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.ScreenshotAsync(new()
111            {
112                Clip = new()
113                {
114                    X = 50,
115                    Y = 650,
116                    Width = 100,
117                    Height = 100,
118                }
119            }));
120
121            StringAssert.Contains("Clipped area is either empty or outside the resulting image", exception.Message);
122        }
123
124        [PlaywrightTest("page-screenshot.spec.ts", "should run in parallel")]
125        public async Task ShouldRunInParallel()
126        {
127            await Page.SetViewportSizeAsync(500, 500);
128            await Page.GotoAsync(Server.Prefix + "/grid.html");
129
130            var tasks = new List<Task<byte[]>>();
131            for (int i = 0; i < 3; ++i)
132            {
133                tasks.Add(Page.ScreenshotAsync(new()
134                {
135                    Clip = new()
136                    {
137                        X = 50 * i,
138                        Y = 0,
139                        Width = 50,
140                        Height = 50
141                    }
142                }));
143            }
144
145            await TaskUtils.WhenAll(tasks);
146            Assert.True(ScreenshotHelper.PixelMatch("grid-cell-1.png", tasks[0].Result));
147        }
148
149        [PlaywrightTest("page-screenshot.spec.ts", "should take fullPage screenshots")]
150        public async Task ShouldTakeFullPageScreenshots()
151        {
152            await Page.SetViewportSizeAsync(500, 500);
153            await Page.GotoAsync(Server.Prefix + "/grid.html");
154            byte[] screenshot = await Page.ScreenshotAsync(new() { FullPage = true });
155            Assert.True(ScreenshotHelper.PixelMatch("screenshot-grid-fullpage.png", screenshot));
156        }
157
158        [PlaywrightTest("page-screenshot.spec.ts", "should restore viewport after fullPage screenshot")]
159        public async Task ShouldRestoreViewportAfterFullPageScreenshot()
160        {
161            await Page.SetViewportSizeAsync(500, 500);
162            await Page.GotoAsync(Server.Prefix + "/grid.html");
163            await Page.ScreenshotAsync(new() { FullPage = true });
164
165            Assert.AreEqual(500, Page.ViewportSize.Width);
166            Assert.AreEqual(500, Page.ViewportSize.Height);
167        }
168
169        [PlaywrightTest("page-screenshot.spec.ts", "should run in parallel in multiple pages")]
170        public async Task ShouldRunInParallelInMultiplePages()
171        {
172            int n = 5;
173            var pageTasks = new List<Task<IPage>>();
174            for (int i = 0; i < n; i++)
175            {
176                async Task<IPage> Func()
177                {
178                    var page = await Context.NewPageAsync();
179                    await page.GotoAsync(Server.Prefix + "/grid.html");
180                    return page;
181                }
182
183                pageTasks.Add(Func());
184            }
185
186            await TaskUtils.WhenAll(pageTasks);
187
188            var screenshotTasks = new List<Task<byte[]>>();
189            for (int i = 0; i < n; i++)
190            {
191                screenshotTasks.Add(pageTasks[i].Result.ScreenshotAsync(new()
192                {
193                    Clip = new()
194                    {
195                        X = 50 * (i % 2),
196                        Y = 0,
197                        Width = 50,
198                        Height = 50
199                    }
200                }));
201            }
202
203            await TaskUtils.WhenAll(screenshotTasks);
204
205            for (int i = 0; i < n; i++)
206            {
207                Assert.True(ScreenshotHelper.PixelMatch($"grid-cell-{i % 2}.png", screenshotTasks[i].Result));
208            }
209
210            var closeTasks = new List<Task>();
211            for (int i = 0; i < n; i++)
212            {
213                closeTasks.Add(pageTasks[i].Result.CloseAsync());
214            }
215
216            await TaskUtils.WhenAll(closeTasks);
217        }
218
219        [PlaywrightTest("page-screenshot.spec.ts", "should allow transparency")]
220        [Skip(SkipAttribute.Targets.Firefox)]
221        public async Task ShouldAllowTransparency()
222        {
223            await Page.SetViewportSizeAsync(50, 150);
224            await Page.GotoAsync(Server.EmptyPage);
225            byte[] screenshot = await Page.ScreenshotAsync(new() { OmitBackground = true });
226
227            Assert.True(ScreenshotHelper.PixelMatch("transparent.png", screenshot));
228        }
229
230        [PlaywrightTest("page-screenshot.spec.ts", "should render white background on jpeg file")]
231        public async Task ShouldRenderWhiteBackgroundOnJpegFile()
232        {
233            await Page.SetViewportSizeAsync(100, 100);
234            await Page.GotoAsync(Server.EmptyPage);
235            byte[] screenshot = await Page.ScreenshotAsync(new()
236            {
237                OmitBackground = true,
238                Type = ScreenshotType.Jpeg,
239            });
240            Assert.True(ScreenshotHelper.PixelMatch("white.jpg", screenshot));
241        }
242
243        [PlaywrightTest("page-screenshot.spec.ts", "should work with odd clip size on Retina displays")]
244        public async Task ShouldWorkWithOddClipSizeOnRetinaDisplays()
245        {
246            byte[] screenshot = await Page.ScreenshotAsync(new()
247            {
248                Clip = new()
249                {
250                    X = 0,
251                    Y = 0,
252                    Width = 11,
253                    Height = 11
254                }
255            });
256
257            Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-odd-size.png", screenshot));
258        }
259
260        [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport")]
261        [Skip(SkipAttribute.Targets.Firefox)]
262        public async Task ShouldWorkWithAMobileViewport()
263        {
264            await using var context = await Browser.NewContextAsync(new()
265            {
266                ViewportSize = new()
267                {
268                    Width = 320,
269                    Height = 480,
270                },
271                IsMobile = true,
272            });
273            var page = await context.NewPageAsync();
274            await page.GotoAsync(Server.Prefix + "/overflow.html");
275            byte[] screenshot = await page.ScreenshotAsync();
276
277            Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile.png", screenshot));
278        }
279
280        [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport and clip")]
281        [Skip(SkipAttribute.Targets.Firefox)]
282        public async Task ShouldWorkWithAMobileViewportAndClip()
283        {
284            await using var context = await Browser.NewContextAsync(new()
285            {
286                ViewportSize = new()
287                {
288                    Width = 320,
289                    Height = 480,
290                },
291                IsMobile = true,
292            });
293            var page = await context.NewPageAsync();
294            await page.GotoAsync(Server.Prefix + "/overflow.html");
295            byte[] screenshot = await page.ScreenshotAsync(new()
296            {
297                Clip = new()
298                {
299                    X = 10,
300                    Y = 10,
301                    Width = 100,
302                    Height = 150
303                }
304            });
305
306            Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile-clip.png", screenshot));
307        }
308
309        [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport and fullPage")]
310        [Skip(SkipAttribute.Targets.Firefox)]
311        public async Task ShouldWorkWithAMobileViewportAndFullPage()
312        {
313            await using var context = await Browser.NewContextAsync(new()
314            {
315                ViewportSize = new()
316                {
317                    Width = 320,
318                    Height = 480,
319                },
320                IsMobile = true,
321            });
322            var page = await context.NewPageAsync();
323            await page.GotoAsync(Server.Prefix + "/overflow-large.html");
324            byte[] screenshot = await page.ScreenshotAsync(new() { FullPage = true });
325
326            Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile-fullpage.png", screenshot));
327        }
328
329        [PlaywrightTest("page-screenshot.spec.ts", "should work for canvas")]
330        public async Task ShouldWorkForCanvas()
331        {
332            await Page.SetViewportSizeAsync(500, 500);
333            await Page.GotoAsync(Server.Prefix + "/screenshots/canvas.html");
334            byte[] screenshot = await Page.ScreenshotAsync();
335
336            Assert.True(ScreenshotHelper.PixelMatch("screenshot-canvas.png", screenshot));
337        }
338
339        [PlaywrightTest("page-screenshot.spec.ts", "should work for webgl")]
340        [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]
341        public async Task ShouldWorkForWebgl()
342        {
343            await Page.SetViewportSizeAsync(640, 480);
344            await Page.GotoAsync(Server.Prefix + "/screenshots/webgl.html");
345            byte[] screenshot = await Page.ScreenshotAsync();
346
347            Assert.True(ScreenshotHelper.PixelMatch("screenshot-webgl.png", screenshot));
348        }
349
350        [PlaywrightTest("page-screenshot.spec.ts", "should work for translateZ")]
351        public async Task ShouldWorkForTranslateZ()
352        {
353            await Page.SetViewportSizeAsync(500, 500);
354            await Page.GotoAsync(Server.Prefix + "/screenshots/translateZ.html");
355            byte[] screenshot = await Page.ScreenshotAsync();
356
357            Assert.True(ScreenshotHelper.PixelMatch("screenshot-translateZ.png", screenshot));
358        }
359
360        [PlaywrightTest("page-screenshot.spec.ts", "should work while navigating")]
361        public async Task ShouldWorkWhileNavigating()
362        {
363            await Page.SetViewportSizeAsync(500, 500);
364            await Page.GotoAsync(Server.Prefix + "/redirectloop1.html");
365
366            for (int i = 0; i < 10; ++i)
367            {
368                try
369                {
370                    await Page.ScreenshotAsync();
371                }
372                catch (Exception ex) when (ex.Message.Contains("Cannot take a screenshot while page is navigating"))
373                {
374                }
375            }
376        }
377
378        [PlaywrightTest("page-screenshot.spec.ts", "should work with device scale factor")]
379        public async Task ShouldWorkWithDeviceScaleFactor()
380        {
381            await using var context = await Browser.NewContextAsync(new()
382            {
383                ViewportSize = new()
384                {
385                    Width = 320,
386                    Height = 480,
387                },
388                DeviceScaleFactor = 2,
389            });
390            var page = await context.NewPageAsync();
391            await page.GotoAsync(Server.Prefix + "/grid.html");
392            byte[] screenshot = await page.ScreenshotAsync();
393
394            Assert.True(ScreenshotHelper.PixelMatch("screenshot-device-scale-factor.png", screenshot));
395        }
396
397        [PlaywrightTest("page-screenshot.spec.ts", "should work with iframe in shadow")]
398        public async Task ShouldWorkWithiFrameInShadow()
399        {
400            await using var context = await Browser.NewContextAsync(new()
401            {
402                ViewportSize = new()
403                {
404                    Width = 500,
405                    Height = 500,
406                },
407            });
408            var page = await context.NewPageAsync();
409            await page.GotoAsync(Server.Prefix + "/grid-iframe-in-shadow.html");
410            byte[] screenshot = await page.ScreenshotAsync();
411
412            Assert.True(ScreenshotHelper.PixelMatch("screenshot-iframe.png", screenshot));
413        }
414
415        [PlaywrightTest("page-screenshot.spec.ts", "path option should work")]
416        public async Task PathOptionShouldWork()
417        {
418            await Page.SetViewportSizeAsync(500, 500);
419            await Page.GotoAsync(Server.Prefix + "/grid.html");
420            using var tmpDir = new TempDirectory();
421            string outputPath = Path.Combine(tmpDir.Path, "screenshot.png");
422            await Page.ScreenshotAsync(new() { Path = outputPath });
423
424            Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", outputPath));
425        }
426
427        [PlaywrightTest("page-screenshot.spec.ts", "path option should create subdirectories")]
428        public async Task PathOptionShouldCreateSubdirectories()
429        {
430            await Page.SetViewportSizeAsync(500, 500);
431            await Page.GotoAsync(Server.Prefix + "/grid.html");
432            using var tmpDir = new TempDirectory();
433            string outputPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "screenshot.png");
434            await Page.ScreenshotAsync(new() { Path = outputPath });
435
436            Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", outputPath));
437        }
438
439        [PlaywrightTest("page-screenshot.spec.ts", "path option should detect joeg")]
440        public async Task PathOptionShouldDetectJpeg()
441        {
442            await Page.SetViewportSizeAsync(100, 100);
443            await Page.GotoAsync(Server.EmptyPage);
444            using var tmpDir = new TempDirectory();
445            string outputPath = Path.Combine(tmpDir.Path, "screenshot.jpg");
446            await Page.ScreenshotAsync(new() { Path = outputPath, OmitBackground = true });
447
448            Assert.True(ScreenshotHelper.PixelMatch("white.jpg", outputPath));
449        }
450
451        [PlaywrightTest("page-screenshot.spec.ts", "path option should throw for unsupported mime type")]
452        public async Task PathOptionShouldThrowForUnsupportedMimeType()
453        {
454            var exception = await PlaywrightAssert.ThrowsAsync<ArgumentException>(() => Page.ScreenshotAsync(new() { Path = "file.txt" }));
455            StringAssert.Contains("path: unsupported mime type \"text/plain\"", exception.Message);
456        }
457    }
458}
459
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)