How to use ShouldDispatchMicrotasksInOrder method of Microsoft.Playwright.Tests.PageClickTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageClickTests.ShouldDispatchMicrotasksInOrder

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageClickTests.cs

Source: PageClickTests.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.Collections.Generic;
27using System.Drawing;
28using System.Threading.Tasks;
29using Microsoft.Playwright.NUnit;
30using NUnit.Framework;
31
32namespace Microsoft.Playwright.Tests
33{
34    public class PageClickTests : PageTestEx
35    {
36        [PlaywrightTest("page-click.spec.ts", "should click the button")]
37        public async Task ShouldClickTheButton()
38        {
39            await Page.GotoAsync(Server.Prefix + "/input/button.html");
40            await Page.ClickAsync("button");
41            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
42        }
43
44        [PlaywrightTest("page-click.spec.ts", "should click svg")]
45        public async Task ShouldClickSvg()
46        {
47            await Page.SetContentAsync([email protected]"
48                <svg height=""100"" width=""100"">
49                  <circle onclick=""javascript:window.__CLICKED=42"" cx=""50"" cy=""50"" r=""40"" stroke=""black"" stroke-width=""3"" fill=""red""/>
50                </svg>
51            ");
52            await Page.ClickAsync("circle");
53            Assert.AreEqual(42, await Page.EvaluateAsync<int>("() => window.__CLICKED"));
54        }
55
56        [PlaywrightTest("page-click.spec.ts", "should click svg")]
57        public async Task ShouldClickTheButtonIfWindowNodeIsRemoved()
58        {
59            await Page.GotoAsync(Server.Prefix + "/input/button.html");
60            await Page.EvaluateAsync("delete window.Node");
61            await Page.ClickAsync("button");
62            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
63        }
64
65        [PlaywrightTest("page-click.spec.ts", "should click on a span with an inline element inside")]
66        public async Task ShouldClickOnASpanWithAnInlineElementInside()
67        {
68            await Page.SetContentAsync([email protected]"
69                <style>
70                span::before {{
71                    content: 'q';
72                }}
73                </style>
74                <span onclick='javascript:window.CLICKED=42'></span>
75            ");
76            await Page.ClickAsync("span");
77            Assert.AreEqual(42, await Page.EvaluateAsync<int>("() => window.CLICKED"));
78        }
79
80        [PlaywrightTest("page-click.spec.ts", "should click the button after navigation")]
81        public async Task ShouldClickTheButtonAfterNavigation()
82        {
83            await Page.GotoAsync(Server.Prefix + "/input/button.html");
84            await Page.ClickAsync("button");
85            await Page.GotoAsync(Server.Prefix + "/input/button.html");
86            await Page.ClickAsync("button");
87            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
88        }
89
90        [PlaywrightTest("page-click.spec.ts", "should click the button after a cross origin navigation")]
91        public async Task ShouldClickTheButtonAfterACrossOriginNavigation()
92        {
93            await Page.GotoAsync(Server.Prefix + "/input/button.html");
94            await Page.ClickAsync("button");
95            await Page.GotoAsync(Server.CrossProcessPrefix + "/input/button.html");
96            await Page.ClickAsync("button");
97            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
98        }
99
100        [PlaywrightTest("page-click.spec.ts", "should click with disabled javascript")]
101        public async Task ShouldClickWithDisabledJavascript()
102        {
103            await using var context = await Browser.NewContextAsync(new() { JavaScriptEnabled = false });
104            var page = await context.NewPageAsync();
105            await page.GotoAsync(Server.Prefix + "/wrappedlink.html");
106            await TaskUtils.WhenAll(
107                page.ClickAsync("a"),
108                page.WaitForNavigationAsync()
109            );
110            Assert.AreEqual(Server.Prefix + "/wrappedlink.html#clicked", page.Url);
111        }
112
113        [PlaywrightTest("page-click.spec.ts", "should click when one of inline box children is outside of viewport")]
114        public async Task ShouldClickWhenOneOfInlineBoxChildrenIsOutsideOfViewport()
115        {
116            await Page.SetContentAsync([email protected]"
117            <style>
118            i {{
119                position: absolute;
120                top: -1000px;
121            }}
122            </style>
123            <span onclick='javascript:window.CLICKED = 42;'><i>woof</i><b>doggo</b></span>
124            ");
125
126            await Page.ClickAsync("span");
127            Assert.AreEqual(42, await Page.EvaluateAsync<int>("() => window.CLICKED"));
128        }
129
130        [PlaywrightTest("page-click.spec.ts", "should select the text by triple clicking")]
131        public async Task ShouldSelectTheTextByTripleClicking()
132        {
133            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
134            const string text = "This is the text that we are going to try to select. Let's see how it goes.";
135            await Page.FillAsync("textarea", text);
136            await Page.ClickAsync("textarea", new() { ClickCount = 3 });
137            Assert.AreEqual(text, await Page.EvaluateAsync<string>(@"() => {
138                const textarea = document.querySelector('textarea');
139                return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
140            }"));
141        }
142
143        [PlaywrightTest("page-click.spec.ts", "should click offscreen buttons")]
144        public async Task ShouldClickOffscreenButtons()
145        {
146            await Page.GotoAsync(Server.Prefix + "/offscreenbuttons.html");
147            var messages = new List<string>();
148            Page.Console += (_, e) => messages.Add(e.Text);
149
150            for (int i = 0; i < 11; ++i)
151            {
152                // We might have scrolled to click a button - reset to (0, 0).
153                await Page.EvaluateAsync("() => window.scrollTo(0, 0)");
154                await Page.ClickAsync($"#btn{i}");
155            }
156            Assert.AreEqual(new List<string>
157            {
158                "button #0 clicked",
159                "button #1 clicked",
160                "button #2 clicked",
161                "button #3 clicked",
162                "button #4 clicked",
163                "button #5 clicked",
164                "button #6 clicked",
165                "button #7 clicked",
166                "button #8 clicked",
167                "button #9 clicked",
168                "button #10 clicked"
169            }, messages);
170        }
171
172        [PlaywrightTest("page-click.spec.ts", "should waitFor visible when already visible")]
173        public async Task ShouldWaitForVisibleWhenAlreadyVisible()
174        {
175            await Page.GotoAsync(Server.Prefix + "/input/button.html");
176            await Page.ClickAsync("button");
177            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
178        }
179
180        [PlaywrightTest("page-click.spec.ts", "should not wait with force")]
181        public async Task ShouldNotWaitWithForce()
182        {
183            await Page.GotoAsync(Server.Prefix + "/input/button.html");
184            await Page.EvalOnSelectorAsync("button", "b => b.style.display = 'none'");
185
186            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(()
187                => Page.ClickAsync("button", new() { Force = true }));
188
189            StringAssert.Contains("Element is not visible", exception.Message);
190            Assert.AreEqual("Was not clicked", await Page.EvaluateAsync<string>("result"));
191        }
192
193        [PlaywrightTest("page-click.spec.ts", "should waitFor display:none to be gone")]
194        public async Task ShouldWaitForDisplayNoneToBeGone()
195        {
196            await Page.GotoAsync(Server.Prefix + "/input/button.html");
197            await Page.EvalOnSelectorAsync("button", "b => b.style.display = 'none'");
198            var clickTask = Page.ClickAsync("button", new() { Timeout = 0 });
199
200            await GiveItAChanceToClick(Page);
201
202            Assert.False(clickTask.IsCompleted);
203            Assert.AreEqual("Was not clicked", await Page.EvaluateAsync<string>("result"));
204
205            await Page.EvalOnSelectorAsync("button", "b => b.style.display = 'block'");
206            await clickTask;
207
208            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
209        }
210
211        [PlaywrightTest("page-click.spec.ts", "should waitFor visibility:hidden to be gone")]
212        public async Task ShouldWaitForVisibilityhiddenToBeGone()
213        {
214            await Page.GotoAsync(Server.Prefix + "/input/button.html");
215            await Page.EvalOnSelectorAsync("button", "b => b.style.visibility = 'hidden'");
216            var clickTask = Page.ClickAsync("button", new() { Timeout = 0 });
217
218            await GiveItAChanceToClick(Page);
219
220            Assert.False(clickTask.IsCompleted);
221            Assert.AreEqual("Was not clicked", await Page.EvaluateAsync<string>("result"));
222
223            await Page.EvalOnSelectorAsync("button", "b => b.style.visibility = 'visible'");
224            await clickTask;
225
226            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
227        }
228
229        [PlaywrightTest("page-click.spec.ts", "should waitFor visible when parent is hidden")]
230        public async Task ShouldWaitForVisibleWhenParentIsHidden()
231        {
232            await Page.GotoAsync(Server.Prefix + "/input/button.html");
233            await Page.EvalOnSelectorAsync("button", "b => b.parentElement.style.display = 'none'");
234            var clickTask = Page.ClickAsync("button", new() { Timeout = 0 });
235
236            await GiveItAChanceToClick(Page);
237
238            Assert.False(clickTask.IsCompleted);
239            Assert.AreEqual("Was not clicked", await Page.EvaluateAsync<string>("result"));
240
241            await Page.EvalOnSelectorAsync("button", "b => b.parentElement.style.display = 'block'");
242            await clickTask;
243
244            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
245        }
246
247        [PlaywrightTest("page-click.spec.ts", "should click wrapped links")]
248        public async Task ShouldClickWrappedLinks()
249        {
250            await Page.GotoAsync(Server.Prefix + "/wrappedlink.html");
251            await Page.ClickAsync("a");
252            Assert.True(await Page.EvaluateAsync<bool>("window.__clicked"));
253        }
254
255        [PlaywrightTest("page-click.spec.ts", "should click on checkbox input and toggle")]
256        public async Task ShouldClickOnCheckboxInputAndToggle()
257        {
258            await Page.GotoAsync(Server.Prefix + "/input/checkbox.html");
259            Assert.Null(await Page.EvaluateAsync<bool?>("result.check"));
260            await Page.ClickAsync("input#agree");
261            Assert.True(await Page.EvaluateAsync<bool>("result.check"));
262            Assert.AreEqual(new[] {
263                "mouseover",
264                "mouseenter",
265                "mousemove",
266                "mousedown",
267                "mouseup",
268                "click",
269                "input",
270                "change"
271            }, await Page.EvaluateAsync<string[]>("result.events"));
272            await Page.ClickAsync("input#agree");
273            Assert.False(await Page.EvaluateAsync<bool>("result.check"));
274        }
275
276        [PlaywrightTest("page-click.spec.ts", "should click on checkbox label and toggle")]
277        public async Task ShouldClickOnCheckboxLabelAndToggle()
278        {
279            await Page.GotoAsync(Server.Prefix + "/input/checkbox.html");
280            Assert.Null(await Page.EvaluateAsync("result.check"));
281            await Page.ClickAsync("label[for=\"agree\"]");
282            Assert.True(await Page.EvaluateAsync<bool>("result.check"));
283            Assert.AreEqual(new[] {
284                "click",
285                "input",
286                "change"
287            }, await Page.EvaluateAsync<string[]>("result.events"));
288            await Page.ClickAsync("label[for=\"agree\"]");
289            Assert.False(await Page.EvaluateAsync<bool>("result.check"));
290        }
291
292        [PlaywrightTest("page-click.spec.ts", "should not hang with touch-enabled viewports")]
293        public async Task ShouldNotHangWithTouchEnabledViewports()
294        {
295            await using var context = await Browser.NewContextAsync(new()
296            {
297                ViewportSize = Playwright.Devices["iPhone 6"].ViewportSize,
298                HasTouch = Playwright.Devices["iPhone 6"].HasTouch,
299            });
300
301            var page = await context.NewPageAsync();
302            await page.Mouse.DownAsync();
303            await page.Mouse.MoveAsync(100, 10);
304            await page.Mouse.UpAsync();
305        }
306
307        [PlaywrightTest("page-click.spec.ts", "should scroll and click the button")]
308        [Ignore("Flacky")]
309        public async Task ShouldScrollAndClickTheButton()
310        {
311            await Page.GotoAsync(Server.Prefix + "/input/scrollable.html");
312            await Page.ClickAsync("#button-5");
313            Assert.AreEqual("clicked", await Page.EvaluateAsync<string>("document.querySelector(\"#button-5\").textContent"));
314            await Page.ClickAsync("#button-80");
315            Assert.AreEqual("clicked", await Page.EvaluateAsync<string>("document.querySelector(\"#button-80\").textContent"));
316        }
317
318        [PlaywrightTest("page-click.spec.ts", "should double click the button")]
319        public async Task ShouldDoubleClickTheButton()
320        {
321            await Page.GotoAsync(Server.Prefix + "/input/button.html");
322            await Page.EvaluateAsync(@"{
323               window.double = false;
324               const button = document.querySelector('button');
325               button.addEventListener('dblclick', event => {
326                 window.double = true;
327               });
328            }");
329            var button = await Page.QuerySelectorAsync("button");
330            await button.DblClickAsync();
331            Assert.True(await Page.EvaluateAsync<bool>("double"));
332            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
333        }
334
335        [PlaywrightTest("page-click.spec.ts", "should click a partially obscured button")]
336        public async Task ShouldClickAPartiallyObscuredButton()
337        {
338            await Page.GotoAsync(Server.Prefix + "/input/button.html");
339            await Page.EvaluateAsync(@"{
340                const button = document.querySelector('button');
341                button.textContent = 'Some really long text that will go offscreen';
342
343                button.style.position = 'absolute';
344                button.style.left = '368px';
345            }");
346            await Page.ClickAsync("button");
347            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
348        }
349
350        [PlaywrightTest("page-click.spec.ts", "should click a rotated button")]
351        public async Task ShouldClickARotatedButton()
352        {
353            await Page.GotoAsync(Server.Prefix + "/input/rotatedButton.html");
354            await Page.ClickAsync("button");
355            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
356        }
357
358        [PlaywrightTest("page-click.spec.ts", "should fire contextmenu event on right click")]
359        public async Task ShouldFireContextmenuEventOnRightClick()
360        {
361            await Page.GotoAsync(Server.Prefix + "/input/scrollable.html");
362            await Page.ClickAsync("#button-8", new() { Button = MouseButton.Right });
363            Assert.AreEqual("context menu", await Page.EvaluateAsync<string>("document.querySelector('#button-8').textContent"));
364        }
365
366        [PlaywrightTest("page-click.spec.ts", "should click links which cause navigation")]
367        public async Task ShouldClickLinksWhichCauseNavigation()
368        {
369            await Page.SetContentAsync($"<a href=\"{Server.EmptyPage}\">empty.html</a>");
370            // This await should not hang.
371            await Page.ClickAsync("a");
372        }
373
374        [PlaywrightTest("page-click.spec.ts", "should click the button inside an iframe")]
375        public async Task ShouldClickTheButtonInsideAnIframe()
376        {
377            await Page.GotoAsync(Server.EmptyPage);
378            await Page.SetContentAsync("<div style=\"width:100px;height:100px\">spacer</div>");
379            await FrameUtils.AttachFrameAsync(Page, "button-test", Server.Prefix + "/input/button.html");
380            var frame = Page.FirstChildFrame();
381            var button = await frame.QuerySelectorAsync("button");
382            await button.ClickAsync();
383            Assert.AreEqual("Clicked", await frame.EvaluateAsync<string>("window.result"));
384        }
385
386        [PlaywrightTest("page-click.spec.ts", "should click the button with fixed position inside an iframe")]
387        [Skip(SkipAttribute.Targets.Chromium, SkipAttribute.Targets.Webkit)]
388        public async Task ShouldClickTheButtonWithFixedPositionInsideAnIframe()
389        {
390            await Page.GotoAsync(Server.EmptyPage);
391            await Page.SetViewportSizeAsync(500, 500);
392            await Page.SetContentAsync("<div style=\"width:100px;height:2000px\">spacer</div>");
393            await FrameUtils.AttachFrameAsync(Page, "button-test", Server.Prefix + "/input/button.html");
394            var frame = Page.FirstChildFrame();
395            await frame.EvalOnSelectorAsync("button", "button => button.style.setProperty('position', 'fixed')");
396            await frame.ClickAsync("button");
397            Assert.AreEqual("Clicked", await frame.EvaluateAsync<string>("window.result"));
398        }
399
400        [PlaywrightTest("page-click.spec.ts", "should click the button with deviceScaleFactor set")]
401        public async Task ShouldClickTheButtonWithDeviceScaleFactorSet()
402        {
403            await using var context = await Browser.NewContextAsync(new()
404            {
405                ViewportSize = new()
406                {
407                    Width = 400,
408                    Height = 400,
409                },
410                DeviceScaleFactor = 5,
411            });
412
413            var page = await context.NewPageAsync();
414            Assert.AreEqual(5, await page.EvaluateAsync<int>("window.devicePixelRatio"));
415            await page.SetContentAsync("<div style=\"width:100px;height:100px\">spacer</div>");
416            await FrameUtils.AttachFrameAsync(page, "button-test", Server.Prefix + "/input/button.html");
417            var frame = page.FirstChildFrame();
418            var button = await frame.QuerySelectorAsync("button");
419            await button.ClickAsync();
420            Assert.AreEqual("Clicked", await frame.EvaluateAsync<string>("window.result"));
421        }
422
423        [PlaywrightTest("page-click.spec.ts", "should click the button with px border with relative point")]
424        public async Task ShouldClickTheButtonWithPxBorderWithRelativePoint()
425        {
426            await Page.GotoAsync(Server.Prefix + "/input/button.html");
427            await Page.EvalOnSelectorAsync("button", "button => button.style.borderWidth = '8px'");
428            await Page.ClickAsync("button", new() { Position = new() { X = 20, Y = 10 } });
429            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("window.result"));
430            // Safari reports border-relative offsetX/offsetY.
431            Assert.AreEqual(TestConstants.IsWebKit ? 20 + 8 : 20, await Page.EvaluateAsync<int>("offsetX"));
432            Assert.AreEqual(TestConstants.IsWebKit ? 10 + 8 : 10, await Page.EvaluateAsync<int>("offsetY"));
433        }
434
435        [PlaywrightTest("page-click.spec.ts", "should click the button with em border with offset")]
436        public async Task ShouldClickTheButtonWithEmBorderWithOffset()
437        {
438            await Page.GotoAsync(Server.Prefix + "/input/button.html");
439            await Page.EvalOnSelectorAsync("button", "button => button.style.borderWidth = '2em'");
440            await Page.EvalOnSelectorAsync("button", "button => button.style.fontSize = '12px'");
441            await Page.ClickAsync("button", new() { Position = new() { X = 20, Y = 10 } });
442            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("window.result"));
443            // Safari reports border-relative offsetX/offsetY.
444            Assert.AreEqual(TestConstants.IsWebKit ? 12 * 2 + 20 : 20, await Page.EvaluateAsync<int>("offsetX"));
445            Assert.AreEqual(TestConstants.IsWebKit ? 12 * 2 + 10 : 10, await Page.EvaluateAsync<int>("offsetY"));
446        }
447
448        [PlaywrightTest("page-click.spec.ts", "should click a very large button with offset")]
449        public async Task ShouldClickAVeryLargeButtonWithOffset()
450        {
451            await Page.GotoAsync(Server.Prefix + "/input/button.html");
452            await Page.EvalOnSelectorAsync("button", "button => button.style.borderWidth = '8px'");
453            await Page.EvalOnSelectorAsync("button", "button => button.style.height = button.style.width = '2000px'");
454            await Page.ClickAsync("button", new() { Position = new() { X = 1900, Y = 1910 } });
455            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("window.result"));
456            // Safari reports border-relative offsetX/offsetY.
457            Assert.AreEqual(TestConstants.IsWebKit ? 1900 + 8 : 1900, await Page.EvaluateAsync<int>("offsetX"));
458            Assert.AreEqual(TestConstants.IsWebKit ? 1910 + 8 : 1910, await Page.EvaluateAsync<int>("offsetY"));
459        }
460
461        [PlaywrightTest("page-click.spec.ts", "should click a button in scrolling container with offset")]
462        public async Task ShouldClickAButtonInScrollingContainerWithOffset()
463        {
464            await Page.GotoAsync(Server.Prefix + "/input/button.html");
465            await Page.EvalOnSelectorAsync("button", @"button => {
466                const container = document.createElement('div');
467                container.style.overflow = 'auto';
468                container.style.width = '200px';
469                container.style.height = '200px';
470                button.parentElement.insertBefore(container, button);
471                container.appendChild(button);
472                button.style.height = '2000px';
473                button.style.width = '2000px';
474                button.style.borderWidth = '8px';
475            }");
476
477            await Page.ClickAsync("button", new() { Position = new() { X = 1900, Y = 1910 } });
478            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("window.result"));
479            // Safari reports border-relative offsetX/offsetY.
480            Assert.AreEqual(TestConstants.IsWebKit ? 1900 + 8 : 1900, await Page.EvaluateAsync<int>("offsetX"));
481            Assert.AreEqual(TestConstants.IsWebKit ? 1910 + 8 : 1910, await Page.EvaluateAsync<int>("offsetY"));
482        }
483
484        [PlaywrightTest("page-click.spec.ts", "should click the button with offset with page scale")]
485        [Skip(SkipAttribute.Targets.Firefox)]
486        public async Task ShouldClickTheButtonWithOffsetWithPageScale()
487        {
488            await using var context = await Browser.NewContextAsync(new()
489            {
490                ViewportSize = new()
491                {
492                    Width = 400,
493                    Height = 400,
494                },
495                IsMobile = true,
496            });
497
498            var page = await context.NewPageAsync();
499
500            await page.GotoAsync(Server.Prefix + "/input/button.html");
501            await page.EvalOnSelectorAsync("button", @"button => {
502                button.style.borderWidth = '8px';
503                document.body.style.margin = '0';
504            }");
505
506            await page.ClickAsync("button", new() { Position = new() { X = 20, Y = 10 } });
507            Assert.AreEqual("Clicked", await page.EvaluateAsync<string>("window.result"));
508
509            var point = BrowserName switch
510            {
511                "chromium" => new(27, 18),
512                "webkit" => new(29, 19),
513                _ => new Point(28, 18),
514            };
515
516            Assert.AreEqual(point.X, Convert.ToInt32(await page.EvaluateAsync<decimal>("pageX")));
517            Assert.AreEqual(point.Y, Convert.ToInt32(await page.EvaluateAsync<decimal>("pageY")));
518        }
519
520        [PlaywrightTest("page-click.spec.ts", "should wait for stable position")]
521        public async Task ShouldWaitForStablePosition()
522        {
523            await Page.GotoAsync(Server.Prefix + "/input/button.html");
524            await Page.EvalOnSelectorAsync("button", @"button => {
525                button.style.transition = 'margin 500ms linear 0s';
526                button.style.marginLeft = '200px';
527                button.style.borderWidth = '0';
528                button.style.width = '200px';
529                button.style.height = '20px';
530                // Set display to 'block'- otherwise Firefox layouts with non-even
531                // values on Linux.
532                button.style.display = 'block';
533                document.body.style.margin = '0';
534            }");
535
536            await Page.ClickAsync("button");
537            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("window.result"));
538            Assert.AreEqual(300, await Page.EvaluateAsync<int>("pageX"));
539            Assert.AreEqual(10, await Page.EvaluateAsync<int>("pageY"));
540        }
541
542        [PlaywrightTest("page-click.spec.ts", "should wait for becoming hit target")]
543        public async Task ShouldWaitForBecomingHitTarget()
544        {
545            await Page.GotoAsync(Server.Prefix + "/input/button.html");
546            await Page.EvalOnSelectorAsync("button", @"button => {
547                button.style.borderWidth = '0';
548                button.style.width = '200px';
549                button.style.height = '20px';
550                document.body.style.margin = '0';
551                document.body.style.position = 'relative';
552                const flyOver = document.createElement('div');
553                flyOver.className = 'flyover';
554                flyOver.style.position = 'absolute';
555                flyOver.style.width = '400px';
556                flyOver.style.height = '20px';
557                flyOver.style.left = '-200px';
558                flyOver.style.top = '0';
559                flyOver.style.background = 'red';
560                document.body.appendChild(flyOver);
561            }");
562
563            var clickTask = Page.ClickAsync("button");
564            Assert.False(clickTask.IsCompleted);
565
566            await Page.EvalOnSelectorAsync(".flyover", "flyOver => flyOver.style.left = '0'");
567            await GiveItAChanceToClick(Page);
568            Assert.False(clickTask.IsCompleted);
569
570            await Page.EvalOnSelectorAsync(".flyover", "flyOver => flyOver.style.left = '200px'");
571            await clickTask;
572            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("window.result"));
573        }
574
575        [PlaywrightTest("page-click.spec.ts", "should wait for becoming hit target with trial run")]
576        public async Task ShouldWaitForBecomingHitTargetWithTrialRun()
577        {
578            await Page.GotoAsync(Server.Prefix + "/input/button.html");
579            await Page.EvalOnSelectorAsync("button", @"button => {
580                button.style.borderWidth = '0';
581                button.style.width = '200px';
582                button.style.height = '20px';
583                document.body.style.margin = '0';
584                document.body.style.position = 'relative';
585                const flyOver = document.createElement('div');
586                flyOver.className = 'flyover';
587                flyOver.style.position = 'absolute';
588                flyOver.style.width = '400px';
589                flyOver.style.height = '20px';
590                flyOver.style.left = '-200px';
591                flyOver.style.top = '0';
592                flyOver.style.background = 'red';
593                document.body.appendChild(flyOver);
594            }");
595
596            var clickTask = Page.ClickAsync("button", new() { Trial = true });
597            Assert.False(clickTask.IsCompleted);
598
599            await Page.EvalOnSelectorAsync(".flyover", "flyOver => flyOver.style.left = '0'");
600            await GiveItAChanceToClick(Page);
601            Assert.False(clickTask.IsCompleted);
602
603            await Page.EvalOnSelectorAsync(".flyover", "flyOver => flyOver.style.left = '200px'");
604            await clickTask;
605            Assert.AreEqual("Was not clicked", await Page.EvaluateAsync<string>("window.result"));
606        }
607
608        [PlaywrightTest("page-click.spec.ts", "trial run should work with short timeout")]
609        public async Task TrialRunShouldWorkWithShortTimeout()
610        {
611            await Page.GotoAsync(Server.Prefix + "/input/button.html");
612            await Page.QuerySelectorAsync("button");
613            await Page.EvalOnSelectorAsync("button", @"button => button.disabled = true");
614            var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.ClickAsync("button", new() { Trial = true, Timeout = 500 }));
615            StringAssert.Contains("click action (trial run)", exception.Message);
616            Assert.AreEqual("Was not clicked", await Page.EvaluateAsync<string>("window.result"));
617        }
618
619        [PlaywrightTest("page-click.spec.ts", "trial run should not click")]
620        public async Task TrialRunShouldNotClick()
621        {
622            await Page.GotoAsync(Server.Prefix + "/input/button.html");
623            await Page.ClickAsync("button", new() { Trial = true });
624            Assert.AreEqual("Was not clicked", await Page.EvaluateAsync<string>("window.result"));
625        }
626
627        [PlaywrightTest("page-click.spec.ts", "trial run should not double click")]
628        public async Task TrialRunShouldNotDoubleClick()
629        {
630            await Page.GotoAsync(Server.Prefix + "/input/button.html");
631            await Page.EvaluateAsync(@"() => {
632                window['double'] = false;
633                const button = document.querySelector('button');
634                button.addEventListener('dblclick', event => {
635                    window['double'] = true;
636                });
637            }");
638            await Page.DblClickAsync("button", new() { Trial = true });
639            Assert.False(await Page.EvaluateAsync<bool>("double"));
640            Assert.AreEqual("Was not clicked", await Page.EvaluateAsync<string>("window.result"));
641        }
642
643        [PlaywrightTest("page-click.spec.ts", "should fail when obscured and not waiting for hit target")]
644        public async Task ShouldFailWhenObscuredAndNotWaitingForHitTarget()
645        {
646            await Page.GotoAsync(Server.Prefix + "/input/button.html");
647            var button = await Page.QuerySelectorAsync("button");
648            await Page.EvalOnSelectorAsync("button", @"button => {
649                document.body.style.position = 'relative';
650                const blocker = document.createElement('div');
651                blocker.style.position = 'absolute';
652                blocker.style.width = '400px';
653                blocker.style.height = '20px';
654                blocker.style.left = '0';
655                blocker.style.top = '0';
656                document.body.appendChild(blocker);
657            }");
658
659            await button.ClickAsync(new() { Force = true });
660            Assert.AreEqual("Was not clicked", await Page.EvaluateAsync<string>("window.result"));
661        }
662
663        [PlaywrightTest("page-click.spec.ts", "should wait for button to be enabled")]
664        public async Task ShouldWaitForButtonToBeEnabled()
665        {
666            await Page.SetContentAsync("<button onclick=\"javascript: window.__CLICKED = true;\" disabled><span>Click target</span></button>");
667            var clickTask = Page.ClickAsync("text=Click target");
668            await GiveItAChanceToClick(Page);
669            Assert.Null(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
670            Assert.False(clickTask.IsCompleted);
671            await Page.EvaluateAsync("() => document.querySelector('button').removeAttribute('disabled')");
672            await clickTask;
673            Assert.True(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
674        }
675
676        [PlaywrightTest("page-click.spec.ts", "should wait for input to be enabled")]
677        public async Task ShouldWaitForInputToBeEnabled()
678        {
679            await Page.SetContentAsync("<input onclick=\"javascript: window.__CLICKED = true;\" disabled>");
680            var clickTask = Page.ClickAsync("input");
681            await GiveItAChanceToClick(Page);
682            Assert.Null(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
683            Assert.False(clickTask.IsCompleted);
684            await Page.EvaluateAsync("() => document.querySelector('input').removeAttribute('disabled')");
685            await clickTask;
686            Assert.True(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
687        }
688
689        [PlaywrightTest("page-click.spec.ts", "should wait for select to be enabled")]
690        public async Task ShouldWaitForSelectToBeEnabled()
691        {
692            await Page.SetContentAsync("<select onclick=\"javascript: window.__CLICKED = true;\" disabled><option selected>Hello</option></select>");
693            var clickTask = Page.ClickAsync("select");
694            await GiveItAChanceToClick(Page);
695            Assert.Null(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
696            Assert.False(clickTask.IsCompleted);
697            await Page.EvaluateAsync("() => document.querySelector('select').removeAttribute('disabled')");
698            await clickTask;
699            Assert.True(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
700        }
701
702        [PlaywrightTest("page-click.spec.ts", "should click disabled div")]
703        public async Task ShouldClickDisabledDiv()
704        {
705            await Page.SetContentAsync("<div onclick=\"javascript: window.__CLICKED = true;\" disabled>Click target</div>");
706            await Page.ClickAsync("text=Click target");
707            Assert.True(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
708        }
709
710        [PlaywrightTest("page-click.spec.ts", "should climb dom for inner label with pointer-events:none")]
711        public async Task ShouldClimbDomForInnerLabelWithPointerEventsNone()
712        {
713            await Page.SetContentAsync("<button onclick=\"javascript: window.__CLICKED = true;\"><label style=\"pointer-events:none\">Click target</label></button>");
714            await Page.ClickAsync("text=Click target");
715            Assert.True(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
716        }
717
718        [PlaywrightTest("page-click.spec.ts", "should climb up to [role=button]")]
719        public async Task ShouldClimbUpToRoleButton()
720        {
721            await Page.SetContentAsync("<div role=button onclick=\"javascript: window.__CLICKED = true;\"><div style=\"pointer-events:none\"><span><div>Click target</div></span></div>");
722            await Page.ClickAsync("text=Click target");
723            Assert.True(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
724        }
725
726        [PlaywrightTest("page-click.spec.ts", "should wait for BUTTON to be clickable when it has pointer-events:none")]
727        public async Task ShouldWaitForButtonToBeClickableWhenItHasPointerEventsNone()
728        {
729            await Page.SetContentAsync("<button onclick=\"javascript: window.__CLICKED = true;\" style=\"pointer-events:none\"><span>Click target</span></button>");
730            var clickTask = Page.ClickAsync("text=Click target");
731            await GiveItAChanceToClick(Page);
732            Assert.Null(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
733            Assert.False(clickTask.IsCompleted);
734            await Page.EvaluateAsync("() => document.querySelector('button').style.removeProperty('pointer-events')");
735            await clickTask;
736            Assert.True(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
737        }
738
739        [PlaywrightTest("page-click.spec.ts", "should wait for LABEL to be clickable when it has pointer-events:none")]
740        public async Task ShouldWaitForLabelToBeClickableWhenItHasPointerEventsNone()
741        {
742            await Page.SetContentAsync("<label onclick=\"javascript: window.__CLICKED = true;\" style=\"pointer-events:none\"><span>Click target</span></label>");
743            var clickTask = Page.ClickAsync("text=Click target");
744
745            for (int i = 0; i < 5; ++i)
746            {
747                Assert.Null(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
748            }
749
750            Assert.False(clickTask.IsCompleted);
751            await Page.EvaluateAsync("() => document.querySelector('label').style.removeProperty('pointer-events')");
752            await clickTask;
753            Assert.True(await Page.EvaluateAsync<bool?>("window.__CLICKED"));
754        }
755
756        [PlaywrightTest("page-click.spec.ts", "should update modifiers correctly")]
757        public async Task ShouldUpdateModifiersCorrectly()
758        {
759            await Page.GotoAsync(Server.Prefix + "/input/button.html");
760            await Page.ClickAsync("button", new() { Modifiers = new[] { KeyboardModifier.Shift } });
761            Assert.True(await Page.EvaluateAsync<bool>("shiftKey"));
762            await Page.ClickAsync("button", new() { Modifiers = Array.Empty<KeyboardModifier>() });
763            Assert.False(await Page.EvaluateAsync<bool>("shiftKey"));
764
765            await Page.Keyboard.DownAsync("Shift");
766
767            await Page.ClickAsync("button", new() { Modifiers = Array.Empty<KeyboardModifier>() });
768            Assert.False(await Page.EvaluateAsync<bool>("shiftKey"));
769
770            await Page.ClickAsync("button");
771            Assert.True(await Page.EvaluateAsync<bool>("shiftKey"));
772
773            await Page.Keyboard.UpAsync("Shift");
774
775            await Page.ClickAsync("button");
776            Assert.False(await Page.EvaluateAsync<bool>("shiftKey"));
777        }
778
779        [PlaywrightTest("page-click.spec.ts", "should click an offscreen element when scroll-behavior is smooth")]
780        public async Task ShouldClickAnOffscreenElementWhenScrollBehaviorIsSmooth()
781        {
782            await Page.SetContentAsync(@$"
783            <div style=""border: 1px solid black; height: 500px; overflow: auto; width: 500px; scroll-behavior: smooth"">
784                <button style=""margin-top: 2000px"" onClick=""window.clicked = true"" >hi</button>
785            </div>");
786
787            await Page.ClickAsync("button");
788            Assert.True(await Page.EvaluateAsync<bool>("window.clicked"));
789        }
790
791        [PlaywrightTest("page-click.spec.ts", "should report nice error when element is detached and force-clicked")]
792        public async Task ShouldReportNiceErrorWhenElementIsDetachedAndForceClicked()
793        {
794            await Page.GotoAsync(Server.Prefix + "/input/animating-button.html");
795            await Page.EvaluateAsync("() => addButton()");
796            var handle = await Page.QuerySelectorAsync("button");
797            await Page.EvaluateAsync("() => stopButton(true)");
798            var clickTask = handle.ClickAsync(new() { Force = true });
799            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => clickTask);
800            Assert.Null(await Page.EvaluateAsync<bool?>("window.clicked"));
801            StringAssert.Contains("Element is not attached to the DOM", exception.Message);
802        }
803
804        [PlaywrightTest("page-click.spec.ts", "should fail when element detaches after animation")]
805        public async Task ShouldFailWhenElementDetachesAfterAnimation()
806        {
807            await Page.GotoAsync(Server.Prefix + "/input/animating-button.html");
808            await Page.EvaluateAsync("() => addButton()");
809            var handle = await Page.QuerySelectorAsync("button");
810            var clickTask = handle.ClickAsync();
811            await Page.EvaluateAsync("() => stopButton(true)");
812            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => clickTask);
813            Assert.Null(await Page.EvaluateAsync<bool?>("window.clicked"));
814            StringAssert.Contains("Element is not attached to the DOM", exception.Message);
815        }
816
817        [PlaywrightTest("page-click.spec.ts", "should retry when element detaches after animation")]
818        public async Task ShouldRetryWhenElementDetachesAfterAnimation()
819        {
820            await Page.GotoAsync(Server.Prefix + "/input/animating-button.html");
821            await Page.EvaluateAsync("() => addButton()");
822            var clickTask = Page.ClickAsync("button");
823            Assert.False(clickTask.IsCompleted);
824            Assert.Null(await Page.EvaluateAsync<bool?>("window.clicked"));
825            await Page.EvaluateAsync("() => stopButton(true)");
826            await Page.EvaluateAsync("() => addButton()");
827            Assert.False(clickTask.IsCompleted);
828            Assert.Null(await Page.EvaluateAsync<bool?>("window.clicked"));
829            await Page.EvaluateAsync("() => stopButton(true)");
830            await Page.EvaluateAsync("() => addButton()");
831            Assert.False(clickTask.IsCompleted);
832            Assert.Null(await Page.EvaluateAsync<bool?>("window.clicked"));
833            await Page.EvaluateAsync("() => stopButton(false)");
834            await clickTask;
835            Assert.True(await Page.EvaluateAsync<bool?>("window.clicked"));
836        }
837
838        [PlaywrightTest("page-click.spec.ts", "should retry when element is animating from outside the viewport")]
839        public async Task ShouldRetryWhenElementIsAnimatingFromOutsideTheViewport()
840        {
841            await Page.SetContentAsync([email protected]"
842                <style>
843                  @keyframes move {{
844                    from {{ left: -300px; }}
845                    to {{ left: 0; }}
846                  }}
847                  button {{
848                    position: absolute;
849                    left: -300px;
850                    top: 0;
851                    bottom: 0;
852                    width: 200px;
853                  }}
854                  button.animated {{
855                    animation: 1s linear 1s move forwards;
856                  }}
857                  </style>
858                  <div style=""position: relative; width: 300px; height: 300px;"">
859                     <button onclick =""window.clicked=true""></button>
860                  </div>");
861
862            var handle = await Page.QuerySelectorAsync("button");
863            var clickTask = handle.ClickAsync();
864            await handle.EvaluateAsync("button => button.className = 'animated'");
865            await clickTask;
866            Assert.True(await Page.EvaluateAsync<bool?>("window.clicked"));
867        }
868
869        [PlaywrightTest("page-click.spec.ts", "should retry when element is animating from outside the viewport with force")]
870        public async Task ShouldRetryWhenElementIsAnimatingFromOutsideTheViewportWithForce()
871        {
872            await Page.SetContentAsync([email protected]"
873                <style>
874                  @keyframes move {{
875                    from {{ left: -300px; }}
876                    to {{ left: 0; }}
877                  }}
878                  button {{
879                    position: absolute;
880                    left: -300px;
881                    top: 0;
882                    bottom: 0;
883                    width: 200px;
884                  }}
885                  button.animated {{
886                    animation: 1s linear 1s move forwards;
887                  }}
888                  </style>
889                  <div style=""position: relative; width: 300px; height: 300px;"">
890                     <button onclick =""window.clicked=true""></button>
891                  </div>");
892
893            var handle = await Page.QuerySelectorAsync("button");
894            var clickTask = handle.ClickAsync(new() { Force = true });
895            await handle.EvaluateAsync("button => button.className = 'animated'");
896            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => clickTask);
897            Assert.Null(await Page.EvaluateAsync<bool?>("window.clicked"));
898            StringAssert.Contains("Element is outside of the viewport", exception.Message);
899        }
900
901        [PlaywrightTest("page-click.spec.ts", "should dispatch microtasks in order")]
902        public async Task ShouldDispatchMicrotasksInOrder()
903        {
904            await Page.SetContentAsync([email protected]"
905                <button id=button>Click me</button>
906                <script>
907                let mutationCount = 0;
908                const observer = new MutationObserver((mutationsList, observer) => {{
909                    for(let mutation of mutationsList)
910                    ++mutationCount;
911                }});
912                observer.observe(document.body, {{ attributes: true, childList: true, subtree: true }});
913                button.addEventListener('mousedown', () => {{
914                    mutationCount = 0;
915                    document.body.appendChild(document.createElement('div'));
916                }});
917                button.addEventListener('mouseup', () => {{
918                    window.result = mutationCount;
919                }});
920                </script>");
921
922            await Page.ClickAsync("button");
923            Assert.AreEqual(1, await Page.EvaluateAsync<int>("window.result"));
924        }
925
926        [PlaywrightTest("page-click.spec.ts", "should click the button when window.innerWidth is corrupted")]
927        public async Task ShouldClickTheButtonWhenWindowInnerWidthIsCorrupted()
928        {
929            await Page.GotoAsync(Server.Prefix + "/input/button.html");
930            await Page.EvaluateAsync(@"() => window.innerWith = 0");
931
932            await Page.ClickAsync("button");
933            Assert.AreEqual("Clicked", await Page.EvaluateAsync<string>("result"));
934        }
935
936        private async Task GiveItAChanceToClick(IPage page)
937        {
938            for (int i = 0; i < 5; i++)
939            {
940                await page.EvaluateAsync("() => new Promise(f => requestAnimationFrame(() => requestAnimationFrame(f)))");
941            }
942        }
943    }
944}
945
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

Most used method in PageClickTests

Trigger ShouldDispatchMicrotasksInOrder code on LambdaTest Cloud Grid

Execute automation tests with ShouldDispatchMicrotasksInOrder on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
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)