How to use ShouldTakeScreenshotOfDisabledButton method of Microsoft.Playwright.Tests.ElementHandleScreenshotTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.ElementHandleScreenshotTests.ShouldTakeScreenshotOfDisabledButton

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

ElementHandleScreenshotTests.cs

Source: ElementHandleScreenshotTests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.IO;
27using System.Linq;
28using System.Threading.Tasks;
29using Microsoft.Playwright.NUnit;
30using NUnit.Framework;
31using SixLabors.ImageSharp;
32
33namespace Microsoft.Playwright.Tests
34{
35    ///<playwright-file>elementhandle-screenshot.spec.ts</playwright-file>
36    public class ElementHandleScreenshotTests : PageTestEx
37    {
38        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work")]
39        public async Task ShouldWork()
40        {
41            await Page.SetViewportSizeAsync(500, 500);
42            await Page.GotoAsync(Server.Prefix + "/grid.html");
43            await Page.EvaluateAsync("window.scrollBy(50, 100)");
44            var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(3)");
45            byte[] screenshot = await elementHandle.ScreenshotAsync();
46            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", screenshot));
47        }
48
49        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take into account padding and border")]
50        public async Task ShouldTakeIntoAccountPaddingAndBorder()
51        {
52            await Page.SetViewportSizeAsync(500, 500);
53            await Page.SetContentAsync(@"
54                <div style=""height: 14px"">oooo</div>
55                <style>div {
56                    border: 2px solid blue;
57                    background: green;
58                    width: 50px;
59                    height: 50px;
60                }
61                </style>
62                <div id=""d""></div>");
63            var elementHandle = await Page.QuerySelectorAsync("div#d");
64            byte[] screenshot = await elementHandle.ScreenshotAsync();
65            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-padding-border.png", screenshot));
66        }
67
68        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should capture full element when larger than viewport in parallel")]
69        public async Task ShouldCaptureFullElementWhenLargerThanViewportInParallel()
70        {
71            await Page.SetViewportSizeAsync(500, 500);
72            await Page.SetContentAsync(@"
73                <div style=""height: 14px"">oooo</div>
74                <style>
75                div.to-screenshot {
76                  border: 1px solid blue;
77                  width: 600px;
78                  height: 600px;
79                  margin-left: 50px;
80                }
81                ::-webkit-scrollbar{
82                  display: none;
83                }
84                </style>
85                <div class=""to-screenshot""></div>
86                <div class=""to-screenshot""></div>
87                <div class=""to-screenshot""></div>
88            ");
89            var elementHandles = await Page.QuerySelectorAllAsync("div.to-screenshot");
90            var screenshotTasks = elementHandles.Select(e => e.ScreenshotAsync()).ToArray();
91            await TaskUtils.WhenAll(screenshotTasks);
92
93            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-larger-than-viewport.png", screenshotTasks.ElementAt(2).Result));
94        }
95
96        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should capture full element when larger than viewport")]
97        public async Task ShouldCaptureFullElementWhenLargerThanViewport()
98        {
99            await Page.SetViewportSizeAsync(500, 500);
100            await Page.SetContentAsync(@"
101                <div style=""height: 14px"">oooo</div>
102                <style>
103                div.to-screenshot {
104                  border: 1px solid blue;
105                  width: 600px;
106                  height: 600px;
107                  margin-left: 50px;
108                }
109                ::-webkit-scrollbar{
110                  display: none;
111                }
112                </style>
113                <div class=""to-screenshot""></div>
114                <div class=""to-screenshot""></div>
115                <div class=""to-screenshot""></div>");
116
117            var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot");
118            byte[] screenshot = await elementHandle.ScreenshotAsync();
119            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-larger-than-viewport.png", screenshot));
120            await TestUtils.VerifyViewportAsync(Page, 500, 500);
121        }
122
123        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should scroll element into view")]
124        public async Task ShouldScrollElementIntoView()
125        {
126            await Page.SetViewportSizeAsync(500, 500);
127            await Page.SetContentAsync(@"
128                <div style=""height: 14px"">oooo</div>
129                <style>div.above {
130                  border: 2px solid blue;
131                  background: red;
132                  height: 1500px;
133                }
134                div.to-screenshot {
135                  border: 2px solid blue;
136                  background: green;
137                  width: 50px;
138                  height: 50px;
139                }
140                </style>
141                <div class=""above""></div>
142                <div class=""to-screenshot""></div>");
143            var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot");
144            byte[] screenshot = await elementHandle.ScreenshotAsync();
145            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-scrolled-into-view.png", screenshot));
146        }
147
148        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should scroll 15000px into view")]
149        public async Task ShouldScroll15000pxIntoView()
150        {
151            await Page.SetViewportSizeAsync(500, 500);
152            await Page.SetContentAsync(@"
153                <div style=""height: 14px"">oooo</div>
154                <style>div.above {
155                  border: 2px solid blue;
156                  background: red;
157                  height: 15000px;
158                }
159                div.to-screenshot {
160                  border: 2px solid blue;
161                  background: green;
162                  width: 50px;
163                  height: 50px;
164                }
165                </style>
166                <div class=""above""></div>
167                <div class=""to-screenshot""></div>");
168            var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot");
169            byte[] screenshot = await elementHandle.ScreenshotAsync();
170            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-scrolled-into-view.png", screenshot));
171        }
172
173        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with a rotated element")]
174        public async Task ShouldWorkWithARotatedElement()
175        {
176            await Page.SetViewportSizeAsync(500, 500);
177            await Page.SetContentAsync(@"
178                <div style='position: absolute;
179                top: 100px;
180                left: 100px;
181                width: 100px;
182                height: 100px;
183                background: green;
184                transform: rotateZ(200deg); '>&nbsp;</div>
185            ");
186            var elementHandle = await Page.QuerySelectorAsync("div");
187            byte[] screenshot = await elementHandle.ScreenshotAsync();
188            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-rotate.png", screenshot));
189        }
190
191        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should fail to screenshot a detached element")]
192        public async Task ShouldFailToScreenshotADetachedElement()
193        {
194            await Page.SetContentAsync("<h1>remove this</h1>");
195            var elementHandle = await Page.QuerySelectorAsync("h1");
196            await Page.EvaluateAsync("element => element.remove()", elementHandle);
197
198            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => elementHandle.ScreenshotAsync());
199            StringAssert.Contains("Element is not attached to the DOM", exception.Message);
200        }
201
202        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should timeout waiting for visible")]
203        public async Task ShouldTimeoutWaitingForVisible()
204        {
205            await Page.SetContentAsync(@"<div style='width: 50px; height: 0'></div>");
206            var elementHandle = await Page.QuerySelectorAsync("div");
207            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => elementHandle.ScreenshotAsync(new() { Timeout = 3000 }));
208            StringAssert.Contains("Timeout 3000ms exceeded", exception.Message);
209            StringAssert.Contains("element is not visible", exception.Message);
210        }
211
212        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should wait for visible")]
213        public async Task ShouldWaitForVisible()
214        {
215            await Page.SetViewportSizeAsync(500, 500);
216            await Page.GotoAsync(Server.Prefix + "/grid.html");
217            await Page.EvaluateAsync("() => window.scrollBy(50, 100)");
218            var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(3)");
219            await elementHandle.EvaluateAsync("e => e.style.visibility = 'hidden'");
220            var task = elementHandle.ScreenshotAsync();
221
222            for (int i = 0; i < 10; i++)
223            {
224                await Page.EvaluateAsync("() => new Promise(f => requestAnimationFrame(f))");
225            }
226            Assert.False(task.IsCompleted);
227            await elementHandle.EvaluateAsync("e => e.style.visibility = 'visible'");
228
229            byte[] screenshot = await task;
230            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", screenshot));
231        }
232
233        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work for an element with fractional dimensions")]
234        public async Task ShouldWorkForAnElementWithFractionalDimensions()
235        {
236            await Page.SetContentAsync("<div style=\"width:48.51px;height:19.8px;border:1px solid black;\"></div>");
237            var elementHandle = await Page.QuerySelectorAsync("div");
238            byte[] screenshot = await elementHandle.ScreenshotAsync();
239            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-fractional.png", screenshot));
240        }
241
242        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with a mobile viewport")]
243        [Skip(SkipAttribute.Targets.Firefox)]
244        public async Task ShouldWorkWithAMobileViewport()
245        {
246            await using var context = await Browser.NewContextAsync(new()
247            {
248                ViewportSize = new()
249                {
250                    Width = 320,
251                    Height = 480,
252                },
253                IsMobile = true,
254            });
255            var page = await context.NewPageAsync();
256            await page.GotoAsync(Server.Prefix + "/grid.html");
257            await page.EvaluateAsync("() => window.scrollBy(50, 100)");
258            var elementHandle = await page.QuerySelectorAsync(".box:nth-of-type(3)");
259            byte[] screenshot = await elementHandle.ScreenshotAsync();
260
261            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-mobile.png", screenshot));
262        }
263
264        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with device scale factor")]
265        [Skip(SkipAttribute.Targets.Firefox)]
266        public async Task ShouldWorkWithDeviceScaleFactor()
267        {
268            await using var context = await Browser.NewContextAsync(new()
269            {
270                ViewportSize = new()
271                {
272                    Width = 320,
273                    Height = 480,
274                },
275                DeviceScaleFactor = 2,
276            });
277            var page = await context.NewPageAsync();
278            await page.GotoAsync(Server.Prefix + "/grid.html");
279            await page.EvaluateAsync("() => window.scrollBy(50, 100)");
280            var elementHandle = await page.QuerySelectorAsync(".box:nth-of-type(3)");
281            byte[] screenshot = await elementHandle.ScreenshotAsync();
282
283            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-mobile-dsf.png", screenshot));
284        }
285
286        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work for an element with an offset")]
287        public async Task ShouldWorkForAnElementWithAnOffset()
288        {
289            await Page.SetContentAsync("<div style=\"position:absolute; top: 10.3px; left: 20.4px;width:50.3px;height:20.2px;border:1px solid black;\"></div>");
290            var elementHandle = await Page.QuerySelectorAsync("div");
291            byte[] screenshot = await elementHandle.ScreenshotAsync();
292            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-fractional-offset.png", screenshot));
293        }
294
295        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take screenshots when default viewport is null")]
296        public async Task ShouldTakeScreenshotsWhenDefaultViewportIsNull()
297        {
298            await using var context = await Browser.NewContextAsync(new()
299            {
300                ViewportSize = ViewportSize.NoViewport
301            });
302            var page = await context.NewPageAsync();
303            await page.SetContentAsync("<div style='height: 10000px; background: red'></div>");
304            var windowSize = await page.EvaluateAsync<ViewportSize>("() => ({ width: window.innerWidth * window.devicePixelRatio, height: window.innerHeight * window.devicePixelRatio })");
305            var sizeBefore = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");
306
307            byte[] screenshot = await page.ScreenshotAsync();
308            Assert.NotNull(screenshot);
309            var decoded = Image.Load(screenshot);
310            Assert.AreEqual(windowSize.Width, decoded.Width);
311            Assert.AreEqual(windowSize.Height, decoded.Height);
312
313            var sizeAfter = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");
314            Assert.AreEqual(sizeBefore.Width, sizeAfter.Width);
315            Assert.AreEqual(sizeBefore.Height, sizeAfter.Height);
316        }
317
318        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take fullPage screenshots when default viewport is null")]
319        public async Task ShouldTakeFullPageScreenshotsWhenDefaultViewportIsNull()
320        {
321            await using var context = await Browser.NewContextAsync(new()
322            {
323                ViewportSize = ViewportSize.NoViewport
324            });
325            var page = await context.NewPageAsync();
326            await page.GotoAsync(Server.Prefix + "/grid.html");
327            var sizeBefore = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");
328
329            byte[] screenshot = await page.ScreenshotAsync(new() { FullPage = true });
330            Assert.NotNull(screenshot);
331
332            var sizeAfter = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");
333            Assert.AreEqual(sizeBefore.Width, sizeAfter.Width);
334            Assert.AreEqual(sizeBefore.Height, sizeAfter.Height);
335        }
336
337        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should restore default viewport after fullPage screenshot")]
338        public async Task ShouldRestoreDefaultViewportAfterFullPageScreenshot()
339        {
340            await using var context = await Browser.NewContextAsync(new()
341            {
342                ViewportSize = new() { Width = 456, Height = 789 },
343            });
344            var page = await context.NewPageAsync();
345            await TestUtils.VerifyViewportAsync(page, 456, 789);
346            byte[] screenshot = await page.ScreenshotAsync(new() { FullPage = true });
347            Assert.NotNull(screenshot);
348
349            await TestUtils.VerifyViewportAsync(page, 456, 789);
350        }
351
352        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take element screenshot when default viewport is null and restore back")]
353        public async Task ShouldTakeElementScreenshotWhenDefaultViewportIsNullAndRestoreBack()
354        {
355            await using var context = await Browser.NewContextAsync(new()
356            {
357                ViewportSize = ViewportSize.NoViewport,
358            });
359            var page = await context.NewPageAsync();
360
361            await page.SetContentAsync(@"
362                <div style=""height: 14px"">oooo</div>
363                <style>
364                div.to-screenshot {
365                border: 1px solid blue;
366                width: 600px;
367                height: 600px;
368                margin-left: 50px;
369                }
370                ::-webkit-scrollbar{
371                display: none;
372                }
373                </style>
374                <div class=""to-screenshot""></div>
375                <div class=""to-screenshot""></div>
376                <div class=""to-screenshot""></div>");
377
378            var sizeBefore = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");
379            var elementHandle = await page.QuerySelectorAsync("div.to-screenshot");
380            byte[] screenshot = await elementHandle.ScreenshotAsync();
381            Assert.NotNull(screenshot);
382
383            var sizeAfter = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");
384            Assert.AreEqual(sizeBefore.Width, sizeAfter.Width);
385            Assert.AreEqual(sizeBefore.Height, sizeAfter.Height);
386        }
387
388        [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take screenshot of disabled button")]
389        public async Task ShouldTakeScreenshotOfDisabledButton()
390        {
391            await Page.SetViewportSizeAsync(500, 500);
392            await Page.SetContentAsync("<button disabled>Click me</button>");
393            var button = await Page.QuerySelectorAsync("button");
394            byte[] screenshot = await button.ScreenshotAsync();
395            Assert.NotNull(screenshot);
396        }
397
398        [PlaywrightTest("elementhandle-screenshot.spec.ts", "path option should create subdirectories")]
399        public async Task PathOptionShouldCreateSubdirectories()
400        {
401            await Page.SetViewportSizeAsync(500, 500);
402            await Page.GotoAsync(Server.Prefix + "/grid.html");
403            await Page.EvaluateAsync("() => window.scrollBy(50, 100)");
404            var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(3)");
405            using var tmpDir = new TempDirectory();
406            string outputPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "screenshot.png");
407            await elementHandle.ScreenshotAsync(new() { Path = outputPath });
408            Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", outputPath));
409        }
410    }
411}
412
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)