How to use ShouldPressTheMetaKey method of PuppeteerSharp.Tests.KeyboardTests.KeyboardTests class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Tests.KeyboardTests.KeyboardTests.ShouldPressTheMetaKey

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

KeyboardTests.cs

Source: KeyboardTests.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.Threading.Tasks;
4using PuppeteerSharp.Input;
5using PuppeteerSharp.Tests.Attributes;
6using PuppeteerSharp.Xunit;
7using Xunit;
8using Xunit.Abstractions;
9
10namespace PuppeteerSharp.Tests.KeyboardTests
11{
12    [Collection(TestConstants.TestFixtureCollectionName)]
13    public class KeyboardTests : PuppeteerPageBaseTest
14    {
15        public KeyboardTests(ITestOutputHelper output) : base(output)
16        {
17        }
18
19        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should type into a textarea")]
20        [PuppeteerFact]
21        public async Task ShouldTypeIntoTheTextarea()
22        {
23            await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");
24
25            var textarea = await Page.QuerySelectorAsync("textarea");
26            await textarea.TypeAsync("Type in this text!");
27            Assert.Equal("Type in this text!", await Page.EvaluateExpressionAsync<string>("result"));
28        }
29
30        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should move with the arrow keys")]
31        [PuppeteerFact]
32        public async Task ShouldMoveWithTheArrowKeys()
33        {
34            await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");
35            await Page.TypeAsync("textarea", "Hello World!");
36            Assert.Equal("Hello World!", await Page.EvaluateExpressionAsync<string>("document.querySelector('textarea').value"));
37            for (var i = 0; i < "World!".Length; i++)
38            {
39                _ = Page.Keyboard.PressAsync("ArrowLeft");
40            }
41
42            await Page.Keyboard.TypeAsync("inserted ");
43            Assert.Equal("Hello inserted World!", await Page.EvaluateExpressionAsync<string>("document.querySelector('textarea').value"));
44            _ = Page.Keyboard.DownAsync("Shift");
45            for (var i = 0; i < "inserted ".Length; i++)
46            {
47                _ = Page.Keyboard.PressAsync("ArrowLeft");
48            }
49
50            _ = Page.Keyboard.UpAsync("Shift");
51            await Page.Keyboard.PressAsync("Backspace");
52            Assert.Equal("Hello World!", await Page.EvaluateExpressionAsync<string>("document.querySelector('textarea').value"));
53        }
54
55        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should send a character with ElementHandle.press")]
56        [PuppeteerFact]
57        public async Task ShouldSendACharacterWithElementHandlePress()
58        {
59            await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");
60            var textarea = await Page.QuerySelectorAsync("textarea");
61            await textarea.PressAsync("a");
62            Assert.Equal("a", await Page.EvaluateExpressionAsync<string>("document.querySelector('textarea').value"));
63
64            await Page.EvaluateExpressionAsync("window.addEventListener('keydown', e => e.preventDefault(), true)");
65
66            await textarea.PressAsync("b");
67            Assert.Equal("a", await Page.EvaluateExpressionAsync<string>("document.querySelector('textarea').value"));
68        }
69
70        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "ElementHandle.press should support |text| option")]
71        [SkipBrowserFact(skipFirefox: true)]
72        public async Task ElementHandlePressShouldSupportTextOption()
73        {
74            await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");
75            var textarea = await Page.QuerySelectorAsync("textarea");
76            await textarea.PressAsync("a", new PressOptions { Text = "ё" });
77            Assert.Equal("ё", await Page.EvaluateExpressionAsync<string>("document.querySelector('textarea').value"));
78        }
79
80        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should send a character with sendCharacter")]
81        [SkipBrowserFact(skipFirefox: true)]
82        public async Task ShouldSendACharacterWithSendCharacter()
83        {
84            await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");
85            await Page.FocusAsync("textarea");
86            await Page.Keyboard.SendCharacterAsync("嗨");
87            Assert.Equal("嗨", await Page.EvaluateExpressionAsync<string>("document.querySelector('textarea').value"));
88            await Page.EvaluateExpressionAsync("window.addEventListener('keydown', e => e.preventDefault(), true)");
89            await Page.Keyboard.SendCharacterAsync("a");
90            Assert.Equal("嗨a", await Page.EvaluateExpressionAsync<string>("document.querySelector('textarea').value"));
91        }
92
93        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should report shiftKey")]
94        [SkipBrowserFact(skipFirefox: true)]
95        public async Task ShouldReportShiftKey()
96        {
97            await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html");
98            var keyboard = Page.Keyboard;
99            var codeForKey = new Dictionary<string, int> { ["Shift"] = 16, ["Alt"] = 18, ["Control"] = 17 };
100            foreach (var modifier in codeForKey)
101            {
102                await keyboard.DownAsync(modifier.Key);
103                Assert.Equal($"Keydown: {modifier.Key} {modifier.Key}Left {modifier.Value} [{modifier.Key}]", await Page.EvaluateExpressionAsync<string>("getResult()"));
104                await keyboard.DownAsync("!");
105                // Shift+! will generate a keypress
106                if (modifier.Key == "Shift")
107                {
108                    Assert.Equal($"Keydown: ! Digit1 49 [{modifier.Key}]\nKeypress: ! Digit1 33 33 [{modifier.Key}]", await Page.EvaluateExpressionAsync<string>("getResult()"));
109                }
110                else
111                {
112                    Assert.Equal($"Keydown: ! Digit1 49 [{modifier.Key}]", await Page.EvaluateExpressionAsync<string>("getResult()"));
113                }
114
115                await keyboard.UpAsync("!");
116                Assert.Equal($"Keyup: ! Digit1 49 [{modifier.Key}]", await Page.EvaluateExpressionAsync<string>("getResult()"));
117                await keyboard.UpAsync(modifier.Key);
118                Assert.Equal($"Keyup: {modifier.Key} {modifier.Key}Left {modifier.Value} []", await Page.EvaluateExpressionAsync<string>("getResult()"));
119            }
120        }
121
122        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should report multiple modifiers")]
123        [PuppeteerFact]
124        public async Task ShouldReportMultipleModifiers()
125        {
126            await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html");
127            var keyboard = Page.Keyboard;
128            await keyboard.DownAsync("Control");
129            Assert.Equal("Keydown: Control ControlLeft 17 [Control]", await Page.EvaluateExpressionAsync<string>("getResult()"));
130            await keyboard.DownAsync("Alt");
131            Assert.Equal("Keydown: Alt AltLeft 18 [Alt Control]", await Page.EvaluateExpressionAsync<string>("getResult()"));
132            await keyboard.DownAsync(";");
133            Assert.Equal("Keydown: ; Semicolon 186 [Alt Control]", await Page.EvaluateExpressionAsync<string>("getResult()"));
134            await keyboard.UpAsync(";");
135            Assert.Equal("Keyup: ; Semicolon 186 [Alt Control]", await Page.EvaluateExpressionAsync<string>("getResult()"));
136            await keyboard.UpAsync("Control");
137            Assert.Equal("Keyup: Control ControlLeft 17 [Alt]", await Page.EvaluateExpressionAsync<string>("getResult()"));
138            await keyboard.UpAsync("Alt");
139            Assert.Equal("Keyup: Alt AltLeft 18 []", await Page.EvaluateExpressionAsync<string>("getResult()"));
140        }
141
142        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should send proper codes while typing")]
143        [PuppeteerFact]
144        public async Task ShouldSendProperCodesWhileTyping()
145        {
146            await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html");
147            await Page.Keyboard.TypeAsync("!");
148            Assert.Equal(string.Join("\n", new[] {
149                "Keydown: ! Digit1 49 []",
150                "Keypress: ! Digit1 33 33 []",
151                "Keyup: ! Digit1 49 []" }), await Page.EvaluateExpressionAsync<string>("getResult()"));
152            await Page.Keyboard.TypeAsync("^");
153            Assert.Equal(string.Join("\n", new[] {
154                "Keydown: ^ Digit6 54 []",
155                "Keypress: ^ Digit6 94 94 []",
156                "Keyup: ^ Digit6 54 []" }), await Page.EvaluateExpressionAsync<string>("getResult()"));
157        }
158
159        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should send proper codes while typing with shift")]
160        [PuppeteerFact]
161        public async Task ShouldSendProperCodesWhileTypingWithShift()
162        {
163            await Page.GoToAsync(TestConstants.ServerUrl + "/input/keyboard.html");
164            var keyboard = Page.Keyboard;
165            await keyboard.DownAsync("Shift");
166            await Page.Keyboard.TypeAsync("~");
167            Assert.Equal(string.Join("\n", new[] {
168                "Keydown: Shift ShiftLeft 16 [Shift]",
169                "Keydown: ~ Backquote 192 [Shift]", // 192 is ` keyCode
170                "Keypress: ~ Backquote 126 126 [Shift]", // 126 is ~ charCode
171                "Keyup: ~ Backquote 192 [Shift]" }), await Page.EvaluateExpressionAsync<string>("getResult()"));
172            await keyboard.UpAsync("Shift");
173        }
174
175        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should not type canceled events")]
176        [PuppeteerFact]
177        public async Task ShouldNotTypeCanceledEvents()
178        {
179            await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");
180            await Page.FocusAsync("textarea");
181            await Page.EvaluateExpressionAsync(@"{
182              window.addEventListener('keydown', event => {
183                event.stopPropagation();
184                event.stopImmediatePropagation();
185                if (event.key === 'l')
186                  event.preventDefault();
187                if (event.key === 'o')
188                  event.preventDefault();
189              }, false);
190            }");
191            await Page.Keyboard.TypeAsync("Hello World!");
192            Assert.Equal("He Wrd!", await Page.EvaluateExpressionAsync<string>("textarea.value"));
193        }
194
195        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should specify repeat property")]
196        [SkipBrowserFact(skipFirefox: true)]
197        public async Task ShouldSpecifyRepeatProperty()
198        {
199            await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");
200            await Page.FocusAsync("textarea");
201            await Page.EvaluateExpressionAsync("document.querySelector('textarea').addEventListener('keydown', e => window.lastEvent = e, true)");
202            await Page.Keyboard.DownAsync("a");
203            Assert.False(await Page.EvaluateExpressionAsync<bool>("window.lastEvent.repeat"));
204            await Page.Keyboard.PressAsync("a");
205            Assert.True(await Page.EvaluateExpressionAsync<bool>("window.lastEvent.repeat"));
206
207            await Page.Keyboard.DownAsync("b");
208            Assert.False(await Page.EvaluateExpressionAsync<bool>("window.lastEvent.repeat"));
209            await Page.Keyboard.DownAsync("b");
210            Assert.True(await Page.EvaluateExpressionAsync<bool>("window.lastEvent.repeat"));
211
212            await Page.Keyboard.UpAsync("a");
213            await Page.Keyboard.DownAsync("a");
214            Assert.False(await Page.EvaluateExpressionAsync<bool>("window.lastEvent.repeat"));
215        }
216
217        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should type all kinds of characters")]
218        [SkipBrowserFact(skipFirefox: true)]
219        public async Task ShouldTypeAllKindsOfCharacters()
220        {
221            await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");
222            await Page.FocusAsync("textarea");
223            const string text = "This text goes onto two lines.\nThis character is 嗨.";
224            await Page.Keyboard.TypeAsync(text);
225            Assert.Equal(text, await Page.EvaluateExpressionAsync<string>("result"));
226        }
227
228        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should specify location")]
229        [SkipBrowserFact(skipFirefox: true)]
230        public async Task ShouldSpecifyLocation()
231        {
232            await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");
233            await Page.EvaluateExpressionAsync(@"{
234              window.addEventListener('keydown', event => window.keyLocation = event.location, true);
235            }");
236            var textarea = await Page.QuerySelectorAsync("textarea");
237
238            await textarea.PressAsync("Digit5");
239            Assert.Equal(0, await Page.EvaluateExpressionAsync<int>("keyLocation"));
240
241            await textarea.PressAsync("ControlLeft");
242            Assert.Equal(1, await Page.EvaluateExpressionAsync<int>("keyLocation"));
243
244            await textarea.PressAsync("ControlRight");
245            Assert.Equal(2, await Page.EvaluateExpressionAsync<int>("keyLocation"));
246
247            await textarea.PressAsync("NumpadSubtract");
248            Assert.Equal(3, await Page.EvaluateExpressionAsync<int>("keyLocation"));
249        }
250
251        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should throw on unknown keys")]
252        [PuppeteerFact]
253        public async Task ShouldThrowOnUnknownKeys()
254        {
255            await Assert.ThrowsAsync<KeyNotFoundException>(() => Page.Keyboard.PressAsync("NotARealKey"));
256
257            await Assert.ThrowsAsync<KeyNotFoundException>(() => Page.Keyboard.PressAsync("ё"));
258
259            await Assert.ThrowsAsync<KeyNotFoundException>(() => Page.Keyboard.PressAsync("😊"));
260        }
261
262        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should type emoji")]
263        [SkipBrowserFact(skipFirefox: true)]
264        public async Task ShouldTypeEmoji()
265        {
266            await Page.GoToAsync(TestConstants.ServerUrl + "/input/textarea.html");
267            await Page.TypeAsync("textarea", "👹 Tokyo street Japan \uD83C\uDDEF\uD83C\uDDF5");
268            Assert.Equal(
269                "👹 Tokyo street Japan \uD83C\uDDEF\uD83C\uDDF5",
270                await Page.QuerySelectorAsync("textarea").EvaluateFunctionAsync<string>("t => t.value"));
271        }
272
273        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should type emoji into an iframe")]
274        [SkipBrowserFact(skipFirefox: true)]
275        public async Task ShouldTypeEmojiIntoAniframe()
276        {
277            await Page.GoToAsync(TestConstants.EmptyPage);
278            await FrameUtils.AttachFrameAsync(Page, "emoji-test", TestConstants.ServerUrl + "/input/textarea.html");
279            var frame = Page.FirstChildFrame();
280            var textarea = await frame.QuerySelectorAsync("textarea");
281            await textarea.TypeAsync("👹 Tokyo street Japan \uD83C\uDDEF\uD83C\uDDF5");
282            Assert.Equal(
283                "👹 Tokyo street Japan \uD83C\uDDEF\uD83C\uDDF5",
284                await frame.QuerySelectorAsync("textarea").EvaluateFunctionAsync<string>("t => t.value"));
285        }
286
287        [PuppeteerTest("keyboard.spec.ts", "Keyboard", "should press the metaKey")]
288        [SkipBrowserFact(skipFirefox: true)]
289        public async Task ShouldPressTheMetaKey()
290        {
291            await Page.EvaluateFunctionAsync(@"() =>
292            {
293                window.result = null;
294                document.addEventListener('keydown', event => {
295                    window.result = [event.key, event.code, event.metaKey];
296                });
297            }");
298            await Page.Keyboard.PressAsync("Meta");
299            const int key = 0;
300            const int code = 1;
301            const int metaKey = 2;
302            var result = await Page.EvaluateExpressionAsync<object[]>("result");
303            Assert.Equal("Meta", result[key]);
304            Assert.Equal("MetaLeft", result[code]);
305            Assert.Equal(true, result[metaKey]);
306        }
307    }
308}
309
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)