How to use PageKeyboardTests class of Microsoft.Playwright.Tests package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageKeyboardTests

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageKeyboardTests.cs

Source: PageKeyboardTests.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.Collections.Generic;
26using System.Dynamic;
27using System.Linq;
28using System.Threading.Tasks;
29using Microsoft.Playwright.NUnit;
30using NUnit.Framework;
31
32namespace Microsoft.Playwright.Tests
33{
34    public class PageKeyboardTests : PageTestEx
35    {
36        [PlaywrightTest("page-keyboard.spec.ts", "should type into a textarea")]
37        public async Task ShouldTypeIntoATextarea()
38        {
39            await Page.EvaluateAsync<string>(@"() => {
40                var textarea = document.createElement('textarea');
41                document.body.appendChild(textarea);
42                textarea.focus();
43            }");
44            string text = "Hello world. I am the text that was typed!";
45            await Page.Keyboard.TypeAsync(text);
46            Assert.AreEqual(text, await Page.EvaluateAsync<string>("() => document.querySelector('textarea').value"));
47        }
48
49        [PlaywrightTest("page-keyboard.spec.ts", "should press the metaKey")]
50        public async Task ShouldPressTheMetaKey1()
51        {
52            await Page.GotoAsync(Server.Prefix + "/empty.html");
53            await Page.EvaluateAsync<string>(@"() => {
54                window.keyPromise = new Promise(resolve => document.addEventListener('keydown', event => resolve(event.key)));
55            }");
56            await Page.Keyboard.PressAsync("Meta");
57            Assert.AreEqual(TestConstants.IsFirefox && !TestConstants.IsMacOSX ? "OS" : "Meta", await Page.EvaluateAsync<string>("keyPromise"));
58        }
59
60        [PlaywrightTest("page-keyboard.spec.ts", "should move with the arrow keys")]
61        public async Task ShouldMoveWithTheArrowKeys()
62        {
63            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
64            await Page.TypeAsync("textarea", "Hello World!");
65            Assert.AreEqual("Hello World!", await Page.EvaluateAsync<string>("() => document.querySelector('textarea').value"));
66            for (int i = 0; i < "World!".Length; i++)
67            {
68                _ = Page.Keyboard.PressAsync("ArrowLeft");
69            }
70            await Page.Keyboard.TypeAsync("inserted ");
71            Assert.AreEqual("Hello inserted World!", await Page.EvaluateAsync<string>("() => document.querySelector('textarea').value"));
72            _ = Page.Keyboard.DownAsync("Shift");
73            for (int i = 0; i < "inserted ".Length; i++)
74            {
75                _ = Page.Keyboard.PressAsync("ArrowLeft");
76            }
77            _ = Page.Keyboard.UpAsync("Shift");
78            await Page.Keyboard.PressAsync("Backspace");
79            Assert.AreEqual("Hello World!", await Page.EvaluateAsync<string>("() => document.querySelector('textarea').value"));
80        }
81
82        [PlaywrightTest("page-keyboard.spec.ts", "should send a character with ElementHandle.press")]
83        public async Task ShouldSendACharacterWithElementHandlePress()
84        {
85            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
86            var textarea = await Page.QuerySelectorAsync("textarea");
87            await textarea.PressAsync("a");
88            Assert.AreEqual("a", await Page.EvaluateAsync<string>("() => document.querySelector('textarea').value"));
89
90            await Page.EvaluateAsync<string>("() => window.addEventListener('keydown', e => e.preventDefault(), true)");
91
92            await textarea.PressAsync("b");
93            Assert.AreEqual("a", await Page.EvaluateAsync<string>("() => document.querySelector('textarea').value"));
94        }
95
96        [PlaywrightTest("page-keyboard.spec.ts", "should send a character with sendCharacter")]
97        public async Task ShouldSendACharacterWithSendCharacter()
98        {
99            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
100            await Page.FocusAsync("textarea");
101            await Page.Keyboard.InsertTextAsync("嗨");
102            Assert.AreEqual("嗨", await Page.EvaluateAsync<string>("() => document.querySelector('textarea').value"));
103            await Page.EvaluateAsync<string>("() => window.addEventListener('keydown', e => e.preventDefault(), true)");
104            await Page.Keyboard.InsertTextAsync("a");
105            Assert.AreEqual("嗨a", await Page.EvaluateAsync<string>("() => document.querySelector('textarea').value"));
106        }
107
108        [PlaywrightTest("page-keyboard.spec.ts", "insertText should only emit input event")]
109        public async Task InsertTextShouldOnlyEmitInputEvent()
110        {
111            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
112            await Page.FocusAsync("textarea");
113
114            var events = await Page.EvaluateHandleAsync(@"() => {
115                const events = [];
116                document.addEventListener('keydown', e => events.push(e.type));
117                document.addEventListener('keyup', e => events.push(e.type));
118                document.addEventListener('keypress', e => events.push(e.type));
119                document.addEventListener('input', e => events.push(e.type));
120                return events;
121            }");
122
123            await Page.Keyboard.InsertTextAsync("hello world");
124            Assert.AreEqual(new[] { "input" }, await events.JsonValueAsync<string[]>());
125        }
126
127        [PlaywrightTest("page-keyboard.spec.ts", "should report shiftKey")]
128        [Skip(SkipAttribute.Targets.Firefox | SkipAttribute.Targets.OSX)]
129        public async Task ShouldReportShiftKey()
130        {
131            await Page.GotoAsync(Server.Prefix + "/input/keyboard.html");
132            var keyboard = Page.Keyboard;
133            var codeForKey = new Dictionary<string, int> { ["Shift"] = 16, ["Alt"] = 18, ["Control"] = 17 };
134            foreach (string modifierKey in codeForKey.Keys)
135            {
136                int modifierValue = codeForKey[modifierKey];
137                await keyboard.DownAsync(modifierKey);
138                Assert.AreEqual($"Keydown: {modifierKey} {modifierKey}Left {modifierValue} [{modifierKey}]", await Page.EvaluateAsync<string>("() => getResult()"));
139                await keyboard.DownAsync("!");
140                // Shift+! will generate a keypress
141                if (modifierKey == "Shift")
142                {
143                    Assert.AreEqual($"Keydown: ! Digit1 49 [{modifierKey}]\nKeypress: ! Digit1 33 33 [{modifierKey}]", await Page.EvaluateAsync<string>("() => getResult()"));
144                }
145                else
146                {
147                    Assert.AreEqual($"Keydown: ! Digit1 49 [{modifierKey}]", await Page.EvaluateAsync<string>("() => getResult()"));
148                }
149
150                await keyboard.UpAsync("!");
151                Assert.AreEqual($"Keyup: ! Digit1 49 [{modifierKey}]", await Page.EvaluateAsync<string>("() => getResult()"));
152                await keyboard.UpAsync(modifierKey);
153                Assert.AreEqual($"Keyup: {modifierKey} {modifierKey}Left {modifierValue} []", await Page.EvaluateAsync<string>("() => getResult()"));
154            }
155        }
156
157        [PlaywrightTest("page-keyboard.spec.ts", "should report multiple modifiers")]
158        public async Task ShouldReportMultipleModifiers()
159        {
160            await Page.GotoAsync(Server.Prefix + "/input/keyboard.html");
161            var keyboard = Page.Keyboard;
162            await keyboard.DownAsync("Control");
163            Assert.AreEqual("Keydown: Control ControlLeft 17 [Control]", await Page.EvaluateAsync<string>("() => getResult()"));
164            await keyboard.DownAsync("Alt");
165            Assert.AreEqual("Keydown: Alt AltLeft 18 [Alt Control]", await Page.EvaluateAsync<string>("() => getResult()"));
166            await keyboard.DownAsync(";");
167            Assert.AreEqual("Keydown: ; Semicolon 186 [Alt Control]", await Page.EvaluateAsync<string>("() => getResult()"));
168            await keyboard.UpAsync(";");
169            Assert.AreEqual("Keyup: ; Semicolon 186 [Alt Control]", await Page.EvaluateAsync<string>("() => getResult()"));
170            await keyboard.UpAsync("Control");
171            Assert.AreEqual("Keyup: Control ControlLeft 17 [Alt]", await Page.EvaluateAsync<string>("() => getResult()"));
172            await keyboard.UpAsync("Alt");
173            Assert.AreEqual("Keyup: Alt AltLeft 18 []", await Page.EvaluateAsync<string>("() => getResult()"));
174        }
175
176        [PlaywrightTest("page-keyboard.spec.ts", "should send proper codes while typing")]
177        public async Task ShouldSendProperCodesWhileTyping()
178        {
179            await Page.GotoAsync(Server.Prefix + "/input/keyboard.html");
180            await Page.Keyboard.TypeAsync("!");
181            Assert.AreEqual(string.Join("\n",
182                "Keydown: ! Digit1 49 []",
183                "Keypress: ! Digit1 33 33 []",
184                "Keyup: ! Digit1 49 []"), await Page.EvaluateAsync<string>("() => getResult()"));
185            await Page.Keyboard.TypeAsync("^");
186            Assert.AreEqual(string.Join("\n",
187                "Keydown: ^ Digit6 54 []",
188                "Keypress: ^ Digit6 94 94 []",
189                "Keyup: ^ Digit6 54 []"), await Page.EvaluateAsync<string>("() => getResult()"));
190        }
191
192        [PlaywrightTest("page-keyboard.spec.ts", "should send proper codes while typing with shift")]
193        public async Task ShouldSendProperCodesWhileTypingWithShift()
194        {
195            await Page.GotoAsync(Server.Prefix + "/input/keyboard.html");
196            var keyboard = Page.Keyboard;
197            await keyboard.DownAsync("Shift");
198            await Page.Keyboard.TypeAsync("~");
199            Assert.AreEqual(string.Join("\n",
200                "Keydown: Shift ShiftLeft 16 [Shift]",
201                "Keydown: ~ Backquote 192 [Shift]", // 192 is ` keyCode
202                "Keypress: ~ Backquote 126 126 [Shift]", // 126 is ~ charCode
203                "Keyup: ~ Backquote 192 [Shift]"), await Page.EvaluateAsync<string>("() => getResult()"));
204            await keyboard.UpAsync("Shift");
205        }
206
207        [PlaywrightTest("page-keyboard.spec.ts", "should not type canceled events")]
208        public async Task ShouldNotTypeCanceledEvents()
209        {
210            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
211            await Page.FocusAsync("textarea");
212            await Page.EvaluateAsync<string>(@"() =>{
213                window.addEventListener('keydown', event => {
214                    event.stopPropagation();
215                    event.stopImmediatePropagation();
216                    if (event.key === 'l')
217                        event.preventDefault();
218                    if (event.key === 'o')
219                        event.preventDefault();
220                }, false);
221            }");
222            await Page.Keyboard.TypeAsync("Hello World!");
223            Assert.AreEqual("He Wrd!", await Page.EvaluateAsync<string>("() => textarea.value"));
224        }
225
226        [PlaywrightTest("page-keyboard.spec.ts", "should press plus")]
227        public async Task ShouldPressPlus()
228        {
229            await Page.GotoAsync(Server.Prefix + "/input/keyboard.html");
230            await Page.Keyboard.PressAsync("+");
231            Assert.AreEqual(
232                string.Join(
233                    "\n",
234                    new[]
235                    {
236                        "Keydown: + Equal 187 []", // 192 is ` keyCode
237                        "Keypress: + Equal 43 43 []", // 126 is ~ charCode
238                        "Keyup: + Equal 187 []"
239                    }),
240                await Page.EvaluateAsync<string>("() => getResult()"));
241        }
242
243        [PlaywrightTest("page-keyboard.spec.ts", "should press shift plus")]
244        public async Task ShouldPressShiftPlus()
245        {
246            await Page.GotoAsync(Server.Prefix + "/input/keyboard.html");
247            await Page.Keyboard.PressAsync("Shift++");
248            Assert.AreEqual(
249                string.Join(
250                    "\n",
251                    new[]
252                    {
253                        "Keydown: Shift ShiftLeft 16 [Shift]",
254                        "Keydown: + Equal 187 [Shift]", // 192 is ` keyCode
255                        "Keypress: + Equal 43 43 [Shift]", // 126 is ~ charCode
256                        "Keyup: + Equal 187 [Shift]",
257                        "Keyup: Shift ShiftLeft 16 []"
258                    }),
259                await Page.EvaluateAsync<string>("() => getResult()"));
260        }
261
262        [PlaywrightTest("page-keyboard.spec.ts", "should support plus-separated modifiers")]
263        public async Task ShouldSupportPlusSeparatedModifiers()
264        {
265            await Page.GotoAsync(Server.Prefix + "/input/keyboard.html");
266            await Page.Keyboard.PressAsync("Shift+~");
267            Assert.AreEqual(
268                string.Join(
269                    "\n",
270                    new[]
271                    {
272                        "Keydown: Shift ShiftLeft 16 [Shift]",
273                        "Keydown: ~ Backquote 192 [Shift]", // 192 is ` keyCode
274                        "Keypress: ~ Backquote 126 126 [Shift]", // 126 is ~ charCode
275                        "Keyup: ~ Backquote 192 [Shift]",
276                        "Keyup: Shift ShiftLeft 16 []"
277                    }),
278                await Page.EvaluateAsync<string>("() => getResult()"));
279        }
280
281        [PlaywrightTest("page-keyboard.spec.ts", "should support multiple plus-separated modifiers")]
282        public async Task ShouldSupportMultiplePlusSeparatedModifiers()
283        {
284            await Page.GotoAsync(Server.Prefix + "/input/keyboard.html");
285            await Page.Keyboard.PressAsync("Control+Shift+~");
286            Assert.AreEqual(
287                string.Join(
288                    "\n",
289                    new[]
290                    {
291                        "Keydown: Control ControlLeft 17 [Control]",
292                        "Keydown: Shift ShiftLeft 16 [Control Shift]",
293                        "Keydown: ~ Backquote 192 [Control Shift]", // 192 is ` keyCode
294                        "Keyup: ~ Backquote 192 [Control Shift]",
295                        "Keyup: Shift ShiftLeft 16 [Control]",
296                        "Keyup: Control ControlLeft 17 []"
297                    }),
298                await Page.EvaluateAsync<string>("() => getResult()"));
299        }
300
301        [PlaywrightTest("page-keyboard.spec.ts", "should shift raw codes")]
302        public async Task ShouldShiftRawCodes()
303        {
304            await Page.GotoAsync(Server.Prefix + "/input/keyboard.html");
305            await Page.Keyboard.PressAsync("Shift+Digit3");
306            Assert.AreEqual(
307                string.Join(
308                    "\n",
309                    new[]
310                    {
311                        "Keydown: Shift ShiftLeft 16 [Shift]",
312                        "Keydown: # Digit3 51 [Shift]", // 51 is # keyCode
313                        "Keypress: # Digit3 35 35 [Shift]", // 35 is # charCode
314                        "Keyup: # Digit3 51 [Shift]",
315                        "Keyup: Shift ShiftLeft 16 []"
316                    }),
317                await Page.EvaluateAsync<string>("() => getResult()"));
318        }
319
320        [PlaywrightTest("page-keyboard.spec.ts", "should specify repeat property")]
321        public async Task ShouldSpecifyRepeatProperty()
322        {
323            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
324            await Page.FocusAsync("textarea");
325            var lastEvent = await CaptureLastKeydownAsync(Page);
326            await Page.EvaluateAsync("() => document.querySelector('textarea').addEventListener('keydown', e => window.lastEvent = e, true)");
327            await Page.Keyboard.DownAsync("a");
328            Assert.False(await lastEvent.EvaluateAsync<bool>("e => e.repeat"));
329            await Page.Keyboard.PressAsync("a");
330            Assert.True(await lastEvent.EvaluateAsync<bool>("e => e.repeat"));
331
332            await Page.Keyboard.DownAsync("b");
333            Assert.False(await lastEvent.EvaluateAsync<bool>("e => e.repeat"));
334            await Page.Keyboard.DownAsync("b");
335            Assert.True(await lastEvent.EvaluateAsync<bool>("e => e.repeat"));
336
337            await Page.Keyboard.UpAsync("a");
338            await Page.Keyboard.DownAsync("a");
339            Assert.False(await lastEvent.EvaluateAsync<bool>("e => e.repeat"));
340        }
341
342        [PlaywrightTest("page-keyboard.spec.ts", "should type all kinds of characters")]
343        public async Task ShouldTypeAllKindsOfCharacters()
344        {
345            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
346            await Page.FocusAsync("textarea");
347            string text = "This text goes onto two lines.\nThis character is 嗨.";
348            await Page.Keyboard.TypeAsync(text);
349            Assert.AreEqual(text, await Page.EvaluateAsync<string>("result"));
350        }
351
352        [PlaywrightTest("page-keyboard.spec.ts", "should specify location")]
353        public async Task ShouldSpecifyLocation()
354        {
355            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
356            var lastEventHandle = await CaptureLastKeydownAsync(Page);
357            var textarea = await Page.QuerySelectorAsync("textarea");
358
359            await textarea.PressAsync("Digit5");
360            Assert.AreEqual(0, await lastEventHandle.EvaluateAsync<int>("e => e.location"));
361
362            await textarea.PressAsync("ControlLeft");
363            Assert.AreEqual(1, await lastEventHandle.EvaluateAsync<int>("e => e.location"));
364
365            await textarea.PressAsync("ControlRight");
366            Assert.AreEqual(2, await lastEventHandle.EvaluateAsync<int>("e => e.location"));
367
368            await textarea.PressAsync("NumpadSubtract");
369            Assert.AreEqual(3, await lastEventHandle.EvaluateAsync<int>("e => e.location"));
370        }
371
372        [PlaywrightTest("page-keyboard.spec.ts", "should press Enter")]
373        public async Task ShouldPressEnter()
374        {
375            await Page.SetContentAsync("<textarea></textarea>");
376            await Page.FocusAsync("textarea");
377            var lastEventHandle = await CaptureLastKeydownAsync(Page);
378
379            await TestEnterKeyAsync("Enter", "Enter", "Enter");
380            await TestEnterKeyAsync("NumpadEnter", "Enter", "NumpadEnter");
381            await TestEnterKeyAsync("\n", "Enter", "Enter");
382            await TestEnterKeyAsync("\r", "Enter", "Enter");
383
384            async Task TestEnterKeyAsync(string key, string expectedKey, string expectedCode)
385            {
386                await Page.Keyboard.PressAsync(key);
387                dynamic lastEvent = await lastEventHandle.JsonValueAsync<ExpandoObject>();
388                Assert.AreEqual(expectedKey, lastEvent.key);
389                Assert.AreEqual(expectedCode, lastEvent.code);
390
391                string value = await Page.EvalOnSelectorAsync<string>("textarea", "t => t.value");
392                Assert.AreEqual("\n", value);
393                await Page.EvalOnSelectorAsync("textarea", "t => t.value = ''");
394            }
395        }
396
397        [PlaywrightTest("page-keyboard.spec.ts", "should throw on unknown keys")]
398        public async Task ShouldThrowOnUnknownKeys()
399        {
400            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.Keyboard.PressAsync("NotARealKey"));
401            Assert.AreEqual("Unknown key: \"NotARealKey\"", exception.Message);
402
403            exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.Keyboard.PressAsync("ё"));
404            Assert.AreEqual("Unknown key: \"ё\"", exception.Message);
405
406            exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.Keyboard.PressAsync("😊"));
407            Assert.AreEqual("Unknown key: \"😊\"", exception.Message);
408        }
409
410        [PlaywrightTest("page-keyboard.spec.ts", "should type emoji")]
411        public async Task ShouldTypeEmoji()
412        {
413            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
414            await Page.TypeAsync("textarea", "👹 Tokyo street Japan 🇯🇵");
415            Assert.AreEqual("👹 Tokyo street Japan 🇯🇵", await Page.EvalOnSelectorAsync<string>("textarea", "textarea => textarea.value"));
416        }
417
418        [PlaywrightTest("page-keyboard.spec.ts", "should type emoji into an iframe")]
419        public async Task ShouldTypeEmojiIntoAnIframe()
420        {
421            await Page.GotoAsync(Server.EmptyPage);
422            await FrameUtils.AttachFrameAsync(Page, "emoji-test", Server.Prefix + "/input/textarea.html");
423            var frame = Page.Frames.ElementAt(1);
424            var textarea = await frame.QuerySelectorAsync("textarea");
425            await textarea.TypeAsync("👹 Tokyo street Japan 🇯🇵");
426            Assert.AreEqual("👹 Tokyo street Japan 🇯🇵", await frame.EvalOnSelectorAsync<string>("textarea", "textarea => textarea.value"));
427        }
428
429        [PlaywrightTest("page-keyboard.spec.ts", "should handle selectAll")]
430        [Skip(SkipAttribute.Targets.Chromium | SkipAttribute.Targets.OSX)]
431        public async Task ShouldHandleSelectAll()
432        {
433            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
434            var textarea = await Page.QuerySelectorAsync("textarea");
435            await textarea.TypeAsync("some text");
436            string modifier = TestConstants.IsMacOSX ? "Meta" : "Control";
437            await Page.Keyboard.DownAsync(modifier);
438            await Page.Keyboard.PressAsync("a");
439            await Page.Keyboard.UpAsync(modifier);
440            await Page.Keyboard.PressAsync("Backspace");
441            Assert.IsEmpty(await Page.EvalOnSelectorAsync<string>("textarea", "textarea => textarea.value"));
442        }
443
444        [PlaywrightTest("page-keyboard.spec.ts", "should be able to prevent selectAll")]
445        [Skip(SkipAttribute.Targets.Chromium | SkipAttribute.Targets.OSX)]
446        public async Task ShouldBeAbleToPreventSelectAll()
447        {
448            await Page.GotoAsync(Server.Prefix + "/input/textarea.html");
449            var textarea = await Page.QuerySelectorAsync("textarea");
450            await textarea.TypeAsync("some text");
451            await Page.EvalOnSelectorAsync("textarea", @"textarea => {
452                textarea.addEventListener('keydown', event => {
453                    if (event.key === 'a' && (event.metaKey || event.ctrlKey))
454                    event.preventDefault();
455                }, false);
456            }");
457            string modifier = TestConstants.IsMacOSX ? "Meta" : "Control";
458            await Page.Keyboard.DownAsync(modifier);
459            await Page.Keyboard.PressAsync("a");
460            await Page.Keyboard.UpAsync(modifier);
461            await Page.Keyboard.PressAsync("Backspace");
462            Assert.AreEqual("some tex", await Page.EvalOnSelectorAsync<string>("textarea", "textarea => textarea.value"));
463        }
464
465        [PlaywrightTest("page-keyboard.spec.ts", "should press the meta key")]
466        public async Task ShouldPressTheMetaKey2()
467        {
468            var lastEventHandle = await CaptureLastKeydownAsync(Page);
469            await Page.Keyboard.PressAsync("Meta");
470            dynamic result = await lastEventHandle.JsonValueAsync<ExpandoObject>();
471            string key = result.key;
472            string code = result.code;
473            bool metaKey = result.metaKey;
474
475            if (TestConstants.IsFirefox && !TestConstants.IsMacOSX)
476            {
477                Assert.AreEqual("OS", key);
478            }
479            else
480            {
481                Assert.AreEqual("Meta", key);
482            }
483
484            if (TestConstants.IsFirefox)
485            {
486                Assert.AreEqual("OSLeft", code);
487            }
488            else
489            {
490                Assert.AreEqual("MetaLeft", code);
491            }
492
493            if (TestConstants.IsFirefox && !TestConstants.IsMacOSX)
494            {
495                Assert.False(metaKey);
496            }
497            else
498            {
499                Assert.True(metaKey);
500            }
501        }
502
503        [PlaywrightTest("page-keyboard.spec.ts", "should work after a cross origin navigation")]
504        public async Task ShouldWorkAfterACrossOriginNavigation()
505        {
506            await Page.GotoAsync(Server.Prefix + "/empty.html");
507            await Page.GotoAsync(Server.CrossProcessPrefix + "/empty.html");
508            var lastEventHandle = await CaptureLastKeydownAsync(Page);
509            await Page.Keyboard.PressAsync("a");
510            dynamic result = await lastEventHandle.JsonValueAsync<ExpandoObject>();
511            Assert.AreEqual("a", result.key);
512        }
513
514        [PlaywrightTest("page-keyboard.spec.ts", "should expose keyIdentifier in webkit")]
515        [Skip(SkipAttribute.Targets.Chromium, SkipAttribute.Targets.Firefox)]
516        public async Task ShouldExposeKeyIdentifierInWebkit()
517        {
518            var lastEventHandle = await CaptureLastKeydownAsync(Page);
519            var keyMap = new Dictionary<string, string>
520            {
521                ["ArrowUp"] = "Up",
522                ["ArrowDown"] = "Down",
523                ["ArrowLeft"] = "Left",
524                ["ArrowRight"] = "Right",
525                ["Backspace"] = "U+0008",
526                ["Tab"] = "U+0009",
527                ["Delete"] = "U+007F",
528                ["a"] = "U+0041",
529                ["b"] = "U+0042",
530                ["F12"] = "F12",
531            };
532
533            foreach (var kv in keyMap)
534            {
535                await Page.Keyboard.PressAsync(kv.Key);
536                Assert.AreEqual(kv.Value, await lastEventHandle.EvaluateAsync<string>("e => e.keyIdentifier"));
537            }
538        }
539
540        [PlaywrightTest("page-keyboard.spec.ts", "should scroll with PageDown")]
541        public async Task ShouldScrollWithPageDown()
542        {
543            await Page.GotoAsync(Server.Prefix + "/input/scrollable.html");
544            await Page.ClickAsync("body");
545            await Page.Keyboard.PressAsync("PageDown");
546            await Page.WaitForFunctionAsync("() => scrollY > 0");
547        }
548
549        private Task<IJSHandle> CaptureLastKeydownAsync(IPage page)
550            => page.EvaluateHandleAsync(@"() => {
551                const lastEvent = {
552                  repeat: false,
553                  location: -1,
554                  code: '',
555                  key: '',
556                  metaKey: false,
557                  keyIdentifier: 'unsupported'
558                };
559                document.addEventListener('keydown', e => {
560                  lastEvent.repeat = e.repeat;
561                  lastEvent.location = e.location;
562                  lastEvent.key = e.key;
563                  lastEvent.code = e.code;
564                  lastEvent.metaKey = e.metaKey;
565                  lastEvent.keyIdentifier = 'keyIdentifier' in e && e.keyIdentifier;
566                }, true);
567                return lastEvent;
568            }");
569    }
570}
571
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)