diff --git a/COMPATIBILITY.md b/COMPATIBILITY.md index e8203cc78..292d432e9 100644 --- a/COMPATIBILITY.md +++ b/COMPATIBILITY.md @@ -162,7 +162,7 @@ Differences: - Upstream's docs site pages that have no counterpart in the port: the page objects page (`docs/page-objects.mdx`, moved to `/page-object-model` in `d30114a`), `e2e feedback` and the `docs/reference/cli.mdx` text about its opt-out variables (`4c1e2e8`), and `examples/` with its registry (`b3ae3a4`, `38b802d`, `a29edcb`, `b54646f`). The migration guides (`docs/migrate/*.mdx`, `8537abc`) are ported: see [Migration guides](#migration-guides). The docs site has .NET-only guides for upstream's five example apps of `caf51eb` (tester-army/e2e#1497: i18n, file upload, location, biometrics, deep links), under [Examples](docs-site/src/content/docs/examples/index.mdx). They are not ports: that commit only adds registry entries that link to separate repositories, so there was no guide text. Each page writes C# tests for the upstream app. The self-healing deep dive (`6fa99ea`) is ported as the [Self-healing tests](README.md#self-healing-tests) section of the guide, since the port has no docs pages for the cache, the trace page, or executors to link to. Known gap: only `e2e explore` prints a run summary, since it is the one command that feeds a run to `ListReporter` (see [List reporter](#list-reporter)): the `Cache 4 replayed · 1 handed off · 1 missed` row is `Format.CacheText` over `Format.StepsCacheTally` (`E2E.Cli`, upstream's `cacheText` and `stepsCacheTally` of `report/format.ts`), which an exploration, with its cache off, never fills, and a test run does not print ([#799](https://github.com/hardkoded/e2e-dotnet/issues/799)) - Parallel workers and serial suites - `test.fail` and the `fail` test option (tester-army/e2e#1539, `732ea8a`): a test expected to fail, whose product failure passes and whose pass fails with `UNEXPECTED_PASS`. It lives in upstream's test registry, scheduler, retry, and reporters (`settleExpectedFailure` runs on a finished attempt), and the port has none of them. NUnit and xUnit v3 own the verdict and the retries, and neither has an expected-failure outcome, so a port would need a new public API of its own -- Playwright's page tests in the testbed suite (tester-army/e2e#1505, `bdf769b`) are ported in slices (hardkoded/e2e-dotnet#1060), as the `playwright` category of `tests/E2E.NUnit.Tests`, against the playground's `/content` route and Playwright's test assets (Apache-2.0, `Testbed/playwright/`, with Playwright's `LICENSE` and `NOTICE`). A test upstream marks `{ fail: 'reason' }` keeps its assertions inside the test-only `Helpers.ExpectedToFailAsync`, which passes while the body fails and fails once it passes. Ported so far: `check`, `wait-for-url`, `locator-list`, `selectors-text`, `fill`, `select-option`, `set-input-files`, `filechooser`, `click`, `click-scroll`, and `elementhandle-scroll-into-view`. Upstream's `select-option` test marked `fail` (a bare string selects by label only) passes in the port, which matches a value or a label, so it has no marker. A missing file reports .NET's `Could not find file`, where upstream shows Node's `ENOENT`. +- Playwright's page tests in the testbed suite (tester-army/e2e#1505, `bdf769b`) are ported in slices (hardkoded/e2e-dotnet#1060), as the `playwright` category of `tests/E2E.NUnit.Tests`, against the playground's `/content` route and Playwright's test assets (Apache-2.0, `Testbed/playwright/`, with Playwright's `LICENSE` and `NOTICE`). A test upstream marks `{ fail: 'reason' }` keeps its assertions inside the test-only `Helpers.ExpectedToFailAsync`, which passes while the body fails and fails once it passes. Ported so far: `check`, `wait-for-url`, `locator-list`, `selectors-text`, `fill`, `select-option`, `set-input-files`, `filechooser`, `click`, `click-scroll`, `elementhandle-scroll-into-view`, and `keyboard`. Upstream's `select-option` test marked `fail` (a bare string selects by label only) passes in the port, which matches a value or a label, so it has no marker. A missing file reports .NET's `Could not find file`, where upstream shows Node's `ENOENT`. - Serial groups (upstream tester-army/e2e#1056, #1470): serial runs, group retries, and skipping the rest of a group after a failure belong to the test runner, which is NUnit or xUnit here, so the port keeps no serial groups. The schema has `serialAttempt.cutRetry` and the serial verdict is read from it, but nothing in the port writes a serial attempt: see [Report document](#report-document) - The out-of-process engine protocol (upstream tester-army/e2e#1232, [#873](https://github.com/hardkoded/e2e-dotnet/issues/873)): the port has no runner and no worker pool, so there is no engine process to talk to. An engine is written in .NET against `IEngine` - Diff-only observations for a custom executor's own model turns. The built-in agent has them (#1022): `#id` lines on the opening screen and on `observe`, and a diff after each action (see [MCP server](#mcp-server) for the presenter). `ExecutorObservation.Text`, which an executor reads from `Observe`, keeps the full `[ref=…]` snapshot, cut at the observation byte budget (see [Agents](#agents)), and a node is addressed by its ref there (`new ExecutorTarget("e12")`), so a custom executor has no presenter of its own. Upstream gives every executor the `#id` view. diff --git a/tests/E2E.NUnit.Tests/Keyboard/PageKeyboardTests.cs b/tests/E2E.NUnit.Tests/Keyboard/PageKeyboardTests.cs new file mode 100644 index 000000000..d62c6323b --- /dev/null +++ b/tests/E2E.NUnit.Tests/Keyboard/PageKeyboardTests.cs @@ -0,0 +1,801 @@ +// Copyright 2026 TesterArmy. +// Modified by Dario Kondratiuk. +// SPDX-License-Identifier: Apache-2.0 + +using static E2E.NUnit.Tests.Helpers; + +namespace E2E.NUnit.Tests.Keyboard; + +/// +/// test.describe('page keyboard') of upstream's apps/testbed/tests/keyboard.e2e.ts (Playwright's page-keyboard.spec.ts). +/// PressSequentiallyAsync stands for page.type(selector, text), and an element press of a key Locator.PressAsync does +/// not name (a code like Digit5) is a focus and a keyboard press. Not ported, as upstream: should send a character with insertText, +/// insertText should only emit input event (no keyboard.insertText); should expose keyIdentifier in webkit (WebKit only); should +/// dispatch insertText after context menu was opened (no keyboard.insertText, and mouse.down presses only the primary button); +/// should type after context menu was opened (mouse.down presses only the primary button). +/// +public sealed class PageKeyboardTests : PlaywrightTest +{ + /// Records the last keydown in window.lastEvent, Playwright's captureLastKeydown. + private const string CaptureLastKeydown = """ + () => { + const lastEvent = { repeat: false, location: -1, code: '', key: '', metaKey: false, keyIdentifier: 'unsupported' }; + window.lastEvent = lastEvent; + document.addEventListener('keydown', (e) => { + lastEvent.repeat = e.repeat; + lastEvent.location = e.location; + lastEvent.key = e.key; + lastEvent.code = e.code; + lastEvent.metaKey = e.metaKey; + lastEvent.keyIdentifier = 'keyIdentifier' in e && typeof e.keyIdentifier === 'string' && e.keyIdentifier; + }, true); + } + """; + + private static readonly bool IsMac = OperatingSystem.IsMacOS(); + + private async Task TextareaValueAsync() => + (await Browser.EvaluateAsync("() => document.querySelector('textarea').value"))!; + + private async Task ResultAsync() => (await Browser.EvaluateAsync("getResult()"))!; + + private static string Lines(params string[] lines) => string.Join('\n', lines); + + [Test] + public async Task Should_type_into_a_textarea() + { + await Browser.GotoAsync("/empty.html"); + await Browser.EvaluateAsync("() => { const textarea = document.createElement('textarea'); document.body.appendChild(textarea); textarea.focus(); }"); + const string text = "Hello world. I am the text that was typed!"; + await Browser.Keyboard.TypeAsync(text); + Assert.That(await TextareaValueAsync(), Is.EqualTo(text)); + } + + [Test] + public async Task Should_move_with_the_arrow_keys() + { + await Browser.GotoAsync("/input/textarea.html"); + await Browser.Locator("textarea").PressSequentiallyAsync("Hello World!"); + Assert.That(await TextareaValueAsync(), Is.EqualTo("Hello World!")); + for (var i = 0; i < "World!".Length; i++) + { + await Browser.Keyboard.PressAsync("ArrowLeft"); + } + + await Browser.Keyboard.TypeAsync("inserted "); + Assert.That(await TextareaValueAsync(), Is.EqualTo("Hello inserted World!")); + await Browser.Keyboard.DownAsync("Shift"); + for (var i = 0; i < "inserted ".Length; i++) + { + await Browser.Keyboard.PressAsync("ArrowLeft"); + } + + await Browser.Keyboard.UpAsync("Shift"); + await Browser.Keyboard.PressAsync("Backspace"); + Assert.That(await TextareaValueAsync(), Is.EqualTo("Hello World!")); + } + + [Test] + public async Task Should_send_a_character_with_ElementHandle_press() + { + await Browser.GotoAsync("/input/textarea.html"); + var textarea = Browser.Locator("textarea"); + await textarea.PressAsync("a"); + Assert.That(await TextareaValueAsync(), Is.EqualTo("a")); + + await Browser.EvaluateAsync("() => window.addEventListener('keydown', (e) => e.preventDefault(), true)"); + + await textarea.PressAsync("b"); + Assert.That(await TextareaValueAsync(), Is.EqualTo("a")); + } + + [Test] + public async Task Should_not_type_text_with_Alt_modifier() + { + await Browser.GotoAsync(Content("
")); + foreach (var locator in new[] { Browser.Locator("input"), Browser.Locator("textarea"), Browser.Locator("div") }) + { + await locator.FocusAsync(); + await Browser.Keyboard.PressAsync("Alt+KeyA"); + await Browser.Keyboard.PressAsync("Alt+Digit1"); + await Browser.Keyboard.PressAsync("Alt+Shift+KeyA"); + await Browser.Keyboard.DownAsync("Alt"); + await Browser.Keyboard.PressAsync("b"); + await Browser.Keyboard.UpAsync("Alt"); + await locator.PressAsync("c"); + } + + await Expect.That(Browser.Locator("input")).ToHaveValueAsync("c"); + await Expect.That(Browser.Locator("textarea")).ToHaveValueAsync("c"); + await Expect.That(Browser.Locator("div")).ToHaveTextAsync("c"); + } + + [Test] + public async Task Should_emit_keydown_keypress_textInput_and_input_when_typing_a_character() + { + await Browser.GotoAsync(Content("")); + await Browser.EvaluateAsync(""" + () => { + window.events = []; + for (const type of ['keydown', 'keypress', 'textInput', 'input', 'keyup']) + document.querySelector('input').addEventListener(type, () => window.events.push(type)); + } + """); + await Browser.Locator("input").FocusAsync(); + await Browser.Keyboard.PressAsync("f"); + Assert.That(await Browser.EvaluateAsync("events"), Is.EqualTo(new[] { "keydown", "keypress", "textInput", "input", "keyup" })); + } + + [Test] + public async Task Should_dispatch_key_events_in_separate_tasks() + { + await Browser.GotoAsync(Content("")); + await Browser.EvaluateAsync(""" + () => { + window.log = []; + const input = document.querySelector('input'); + for (const type of ['keydown', 'keypress']) + input.addEventListener(type, () => { window.log.push(type); queueMicrotask(() => window.log.push('microtask-' + type)); }); + input.focus(); + } + """); + await Browser.Keyboard.PressAsync("a"); + Assert.That(await Browser.EvaluateAsync("log"), Is.EqualTo(new[] { "keydown", "microtask-keydown", "keypress", "microtask-keypress" })); + } + + [Test] + public async Task Should_report_shiftKey() + { + await Browser.GotoAsync("/input/keyboard.html"); + var keyboard = Browser.Keyboard; + foreach (var modifierKey in new[] { "Shift", "Alt", "Control" }) + { + await keyboard.DownAsync(modifierKey); + Assert.That(await ResultAsync(), Is.EqualTo("Keydown: " + modifierKey + " " + modifierKey + "Left LEFT [" + modifierKey + "]")); + await keyboard.DownAsync("!"); + if (modifierKey == "Shift") + { + Assert.That(await ResultAsync(), Is.EqualTo("Keydown: ! Digit1 STANDARD [" + modifierKey + "]\nKeypress: ! Digit1 STANDARD 33 [" + modifierKey + "]")); + } + else + { + Assert.That(await ResultAsync(), Is.EqualTo("Keydown: ! Digit1 STANDARD [" + modifierKey + "]")); + } + + await keyboard.UpAsync("!"); + Assert.That(await ResultAsync(), Is.EqualTo("Keyup: ! Digit1 STANDARD [" + modifierKey + "]")); + await keyboard.UpAsync(modifierKey); + Assert.That(await ResultAsync(), Is.EqualTo("Keyup: " + modifierKey + " " + modifierKey + "Left LEFT []")); + } + } + + [Test] + public async Task Should_report_multiple_modifiers() + { + await Browser.GotoAsync("/input/keyboard.html"); + var keyboard = Browser.Keyboard; + await keyboard.DownAsync("Control"); + Assert.That(await ResultAsync(), Is.EqualTo("Keydown: Control ControlLeft LEFT [Control]")); + await keyboard.DownAsync("Alt"); + Assert.That(await ResultAsync(), Is.EqualTo("Keydown: Alt AltLeft LEFT [Alt Control]")); + await keyboard.DownAsync(";"); + Assert.That(await ResultAsync(), Is.EqualTo("Keydown: ; Semicolon STANDARD [Alt Control]")); + await keyboard.UpAsync(";"); + Assert.That(await ResultAsync(), Is.EqualTo("Keyup: ; Semicolon STANDARD [Alt Control]")); + await keyboard.UpAsync("Control"); + Assert.That(await ResultAsync(), Is.EqualTo("Keyup: Control ControlLeft LEFT [Alt]")); + await keyboard.UpAsync("Alt"); + Assert.That(await ResultAsync(), Is.EqualTo("Keyup: Alt AltLeft LEFT []")); + } + + [Test] + public async Task Should_send_proper_codes_while_typing() + { + await Browser.GotoAsync("/input/keyboard.html"); + await Browser.Keyboard.TypeAsync("!"); + Assert.That( + await ResultAsync(), + Is.EqualTo(Lines("Keydown: ! Digit1 STANDARD []", "Keypress: ! Digit1 STANDARD 33 []", "Keyup: ! Digit1 STANDARD []"))); + await Browser.Keyboard.TypeAsync("^"); + Assert.That( + await ResultAsync(), + Is.EqualTo(Lines("Keydown: ^ Digit6 STANDARD []", "Keypress: ^ Digit6 STANDARD 94 []", "Keyup: ^ Digit6 STANDARD []"))); + } + + [Test] + public async Task Should_send_proper_codes_while_typing_with_shift() + { + await Browser.GotoAsync("/input/keyboard.html"); + var keyboard = Browser.Keyboard; + await keyboard.DownAsync("Shift"); + await Browser.Keyboard.TypeAsync("~"); + Assert.That( + await ResultAsync(), + Is.EqualTo(Lines( + "Keydown: Shift ShiftLeft LEFT [Shift]", + "Keydown: ~ Backquote STANDARD [Shift]", + "Keypress: ~ Backquote STANDARD 126 [Shift]", + "Keyup: ~ Backquote STANDARD [Shift]"))); + await keyboard.UpAsync("Shift"); + } + + [Test] + public async Task Should_not_type_canceled_events() + { + await Browser.GotoAsync("/input/textarea.html"); + await Browser.Locator("textarea").FocusAsync(); + await Browser.EvaluateAsync(""" + () => { + window.addEventListener('keydown', (event) => { + event.stopPropagation(); + event.stopImmediatePropagation(); + if (event.key === 'l') + event.preventDefault(); + if (event.key === 'o') + event.preventDefault(); + }, false); + } + """); + await Browser.Keyboard.TypeAsync("Hello World!"); + Assert.That(await TextareaValueAsync(), Is.EqualTo("He Wrd!")); + } + + [Test] + public async Task Should_press_plus() + { + await Browser.GotoAsync("/input/keyboard.html"); + await Browser.Keyboard.PressAsync("+"); + Assert.That( + await ResultAsync(), + Is.EqualTo(Lines("Keydown: + Equal STANDARD []", "Keypress: + Equal STANDARD 43 []", "Keyup: + Equal STANDARD []"))); + } + + [Test] + public async Task Should_press_shift_plus() + { + await Browser.GotoAsync("/input/keyboard.html"); + await Browser.Keyboard.PressAsync("Shift++"); + Assert.That( + await ResultAsync(), + Is.EqualTo(Lines( + "Keydown: Shift ShiftLeft LEFT [Shift]", + "Keydown: + Equal STANDARD [Shift]", + "Keypress: + Equal STANDARD 43 [Shift]", + "Keyup: + Equal STANDARD [Shift]", + "Keyup: Shift ShiftLeft LEFT []"))); + } + + [Test] + public async Task Should_support_plus_separated_modifiers() + { + await Browser.GotoAsync("/input/keyboard.html"); + await Browser.Keyboard.PressAsync("Shift+~"); + Assert.That( + await ResultAsync(), + Is.EqualTo(Lines( + "Keydown: Shift ShiftLeft LEFT [Shift]", + "Keydown: ~ Backquote STANDARD [Shift]", + "Keypress: ~ Backquote STANDARD 126 [Shift]", + "Keyup: ~ Backquote STANDARD [Shift]", + "Keyup: Shift ShiftLeft LEFT []"))); + } + + [Test] + public async Task Should_support_multiple_plus_separated_modifiers() + { + await Browser.GotoAsync("/input/keyboard.html"); + await Browser.Keyboard.PressAsync("Control+Shift+~"); + Assert.That( + await ResultAsync(), + Is.EqualTo(Lines( + "Keydown: Control ControlLeft LEFT [Control]", + "Keydown: Shift ShiftLeft LEFT [Control Shift]", + "Keydown: ~ Backquote STANDARD [Control Shift]", + "Keyup: ~ Backquote STANDARD [Control Shift]", + "Keyup: Shift ShiftLeft LEFT [Control]", + "Keyup: Control ControlLeft LEFT []"))); + } + + [Test] + public async Task Should_shift_raw_codes() + { + await Browser.GotoAsync("/input/keyboard.html"); + await Browser.Keyboard.PressAsync("Shift+Digit3"); + Assert.That( + await ResultAsync(), + Is.EqualTo(Lines( + "Keydown: Shift ShiftLeft LEFT [Shift]", + "Keydown: # Digit3 STANDARD [Shift]", + "Keypress: # Digit3 STANDARD 35 [Shift]", + "Keyup: # Digit3 STANDARD [Shift]", + "Keyup: Shift ShiftLeft LEFT []"))); + } + + [Test] + public async Task Should_specify_repeat_property() + { + await Browser.GotoAsync("/input/textarea.html"); + await Browser.Locator("textarea").FocusAsync(); + await Browser.EvaluateAsync(CaptureLastKeydown); + await Browser.Keyboard.DownAsync("a"); + Assert.That(await Browser.EvaluateAsync("lastEvent.repeat"), Is.False); + await Browser.Keyboard.PressAsync("a"); + Assert.That(await Browser.EvaluateAsync("lastEvent.repeat"), Is.True); + + await Browser.Keyboard.DownAsync("b"); + Assert.That(await Browser.EvaluateAsync("lastEvent.repeat"), Is.False); + await Browser.Keyboard.DownAsync("b"); + Assert.That(await Browser.EvaluateAsync("lastEvent.repeat"), Is.True); + + await Browser.Keyboard.UpAsync("a"); + await Browser.Keyboard.DownAsync("a"); + Assert.That(await Browser.EvaluateAsync("lastEvent.repeat"), Is.False); + } + + [Test] + public async Task Should_type_all_kinds_of_characters() + { + await Browser.GotoAsync("/input/textarea.html"); + await Browser.Locator("textarea").FocusAsync(); + const string text = "This text goes onto two lines.\nThis character is 嗨."; + await Browser.Keyboard.TypeAsync(text); + Assert.That(await TextareaValueAsync(), Is.EqualTo(text)); + } + + /// Reads lastEvent's location, key, and code and checks them together, Playwright's three expect.soft calls. + private async Task ExpectLastKeydownAsync(int location, string key, string code) + { + var actualLocation = await Browser.EvaluateAsync("lastEvent.location"); + var actualKey = await Browser.EvaluateAsync("lastEvent.key"); + var actualCode = await Browser.EvaluateAsync("lastEvent.code"); + Assert.Multiple(() => + { + Assert.That(actualLocation, Is.EqualTo(location)); + Assert.That(actualKey, Is.EqualTo(key)); + Assert.That(actualCode, Is.EqualTo(code)); + }); + } + + [Test] + public async Task Should_specify_location() + { + await Browser.GotoAsync("/input/textarea.html"); + await Browser.EvaluateAsync(CaptureLastKeydown); + var textarea = Browser.Locator("textarea"); + + await textarea.FocusAsync(); + await Browser.Keyboard.PressAsync("Digit5"); + await ExpectLastKeydownAsync(0, "5", "Digit5"); + + await textarea.FocusAsync(); + await Browser.Keyboard.PressAsync("ControlLeft"); + await ExpectLastKeydownAsync(1, "Control", "ControlLeft"); + + await textarea.FocusAsync(); + await Browser.Keyboard.PressAsync("ControlRight"); + await ExpectLastKeydownAsync(2, "Control", "ControlRight"); + + await textarea.FocusAsync(); + await Browser.Keyboard.PressAsync("NumpadSubtract"); + await ExpectLastKeydownAsync(3, "-", "NumpadSubtract"); + } + + [Test] + public async Task Should_specify_numpad_location_on_keyup() + { + await Browser.GotoAsync("/input/keyboard.html"); + await Browser.Keyboard.PressAsync("NumpadSubtract"); + Assert.That( + await ResultAsync(), + Is.EqualTo(Lines("Keydown: - NumpadSubtract NUMPAD []", "Keypress: - NumpadSubtract NUMPAD 45 []", "Keyup: - NumpadSubtract NUMPAD []"))); + } + + [Test] + public async Task Should_press_NumpadDecimal_as_Delete() + { + await Browser.GotoAsync(Content("")); + await Browser.EvaluateAsync(CaptureLastKeydown); + var textarea = Browser.Locator("textarea"); + + await textarea.FocusAsync(); + await Browser.Keyboard.PressAsync("NumpadDecimal"); + Assert.That(await Browser.EvaluateAsync("lastEvent.key"), Is.EqualTo("Delete")); + Assert.That(await Browser.EvaluateAsync("lastEvent.code"), Is.EqualTo("NumpadDecimal")); + Assert.That(await Browser.EvaluateAsync("lastEvent.location"), Is.EqualTo(3)); + await Expect.That(textarea).ToHaveValueAsync(""); + } + + [Test] + public async Task Should_type_numpad_digits_with_Shift() + { + await Browser.GotoAsync(Content("")); + var textarea = Browser.Locator("textarea"); + await textarea.FocusAsync(); + await Browser.Keyboard.PressAsync("Shift+Numpad1"); + await Browser.Keyboard.PressAsync("Shift+NumpadDecimal"); + await Browser.Keyboard.PressAsync("Shift+Numpad9"); + await Expect.That(textarea).ToHaveValueAsync("1.9"); + } + + [Test] + public async Task Should_press_Enter() + { + await Browser.GotoAsync(Content("")); + await Browser.Locator("textarea").FocusAsync(); + await Browser.EvaluateAsync(CaptureLastKeydown); + foreach (var (key, expectedKey, expectedCode) in new[] + { + ("Enter", "Enter", "Enter"), + ("NumpadEnter", "Enter", "NumpadEnter"), + ("\n", "Enter", "Enter"), + ("\r", "Enter", "Enter"), + }) + { + await Browser.Keyboard.PressAsync(key); + Assert.That(await Browser.EvaluateAsync("lastEvent.key"), Is.EqualTo(expectedKey)); + Assert.That(await Browser.EvaluateAsync("lastEvent.code"), Is.EqualTo(expectedCode)); + Assert.That(await TextareaValueAsync(), Is.EqualTo("\n")); + await Browser.EvaluateAsync("() => { document.querySelector('textarea').value = ''; }"); + } + } + + [Test] + public async Task Should_press_audio_and_media_control_keys() + { + await Browser.GotoAsync(Content("")); + await Browser.Locator("input").FocusAsync(); + await Browser.EvaluateAsync(CaptureLastKeydown); + foreach (var mediaKey in new[] { "AudioVolumeMute", "AudioVolumeDown", "AudioVolumeUp", "MediaTrackNext", "MediaTrackPrevious", "MediaPlayPause" }) + { + await Browser.Keyboard.PressAsync(mediaKey); + await ExpectLastKeydownAsync(0, mediaKey, mediaKey); + } + } + + [Test] + public async Task Should_throw_on_unknown_keys() + { + await Browser.GotoAsync("/empty.html"); + foreach (var key in new[] { "NotARealKey", "ё", "😊" }) + { + var error = await Assert.CatchAsync(() => Browser.Keyboard.PressAsync(key)); + Assert.That(error!.Message, Does.Contain($"Unknown key: \"{key}\"")); + } + } + + [Test] + public async Task Should_type_emoji() + { + await Browser.GotoAsync("/input/textarea.html"); + await Browser.Locator("textarea").PressSequentiallyAsync("👹 Tokyo street Japan 🇯🇵"); + Assert.That(await TextareaValueAsync(), Is.EqualTo("👹 Tokyo street Japan 🇯🇵")); + } + + [Test] + public async Task Should_type_emoji_into_an_iframe() + { + await Browser.GotoAsync("/empty.html"); + await Browser.EvaluateAsync(""" + () => new Promise((resolve) => { + const frame = document.createElement('iframe'); + frame.id = 'emoji-test'; + frame.src = '/input/textarea.html'; + frame.onload = resolve; + document.body.appendChild(frame); + }) + """); + await Browser.FrameLocator("#emoji-test").Locator("textarea").PressSequentiallyAsync("👹 Tokyo street Japan 🇯🇵"); + Assert.That( + await Browser.EvaluateAsync("() => document.querySelector('#emoji-test').contentDocument.querySelector('textarea').value"), + Is.EqualTo("👹 Tokyo street Japan 🇯🇵")); + } + + [Test] + public async Task Should_handle_selectAll() + { + await Browser.GotoAsync("/input/textarea.html"); + await Browser.Locator("textarea").PressSequentiallyAsync("some text"); + await Browser.Keyboard.DownAsync("ControlOrMeta"); + await Browser.Keyboard.PressAsync("a"); + await Browser.Keyboard.UpAsync("ControlOrMeta"); + await Browser.Keyboard.PressAsync("Backspace"); + Assert.That(await TextareaValueAsync(), Is.EqualTo("")); + } + + [Test] + public async Task Pressing_Meta_should_not_result_in_any_text_insertion_on_any_platform() + { + await Browser.GotoAsync(Content("")); + var input = Browser.Locator("input"); + await Expect.That(input).ToHaveValueAsync("hello world"); + await input.FocusAsync(); + await Browser.Keyboard.PressAsync("Meta"); + await Expect.That(input).ToHaveValueAsync("hello world"); + } + + [Test] + public async Task Should_be_able_to_prevent_selectAll() + { + await Browser.GotoAsync("/input/textarea.html"); + await Browser.Locator("textarea").PressSequentiallyAsync("some text"); + await Browser.EvaluateAsync(""" + () => { + document.querySelector('textarea').addEventListener('keydown', (event) => { + if (event.key === 'a' && (event.metaKey || event.ctrlKey)) + event.preventDefault(); + }, false); + } + """); + await Browser.Keyboard.DownAsync("ControlOrMeta"); + await Browser.Keyboard.PressAsync("a"); + await Browser.Keyboard.UpAsync("ControlOrMeta"); + await Browser.Keyboard.PressAsync("Backspace"); + Assert.That(await TextareaValueAsync(), Is.EqualTo("some tex")); + } + + [Test] + public async Task Should_support_MacOS_shortcuts() + { + Assume.That(IsMac, Is.True, "macOS only"); + await Browser.GotoAsync("/input/textarea.html"); + await Browser.Locator("textarea").PressSequentiallyAsync("some text"); + await Browser.Keyboard.PressAsync("Shift+Control+Alt+KeyB"); + await Browser.Keyboard.PressAsync("Backspace"); + Assert.That(await TextareaValueAsync(), Is.EqualTo("some ")); + } + + [Test] + public async Task Should_press_the_meta_key() + { + await Browser.GotoAsync("/empty.html"); + await Browser.EvaluateAsync(CaptureLastKeydown); + await Browser.Keyboard.PressAsync("Meta"); + var last = (await Browser.EvaluateAsync("lastEvent"))!; + Assert.That(last.Key, Is.EqualTo("Meta")); + Assert.That(last.Code, Is.EqualTo("MetaLeft")); + Assert.That(last.MetaKey, Is.True); + } + + [Test] + public async Task Should_work_with_keyboard_events_with_empty_html() + { + await Browser.GotoAsync("/empty.html"); + await Browser.EvaluateAsync(CaptureLastKeydown); + await Browser.Keyboard.PressAsync("a"); + Assert.That(await Browser.EvaluateAsync("lastEvent.key"), Is.EqualTo("a")); + } + + [Test] + public async Task Should_work_after_a_cross_origin_navigation() + { + await Browser.GotoAsync("/empty.html"); + await Browser.GotoAsync($"{CROSS}/empty.html"); + await Browser.EvaluateAsync(CaptureLastKeydown); + await Browser.Keyboard.PressAsync("a"); + Assert.That(await Browser.EvaluateAsync("lastEvent.key"), Is.EqualTo("a")); + } + + [Test] + public async Task Should_scroll_with_PageDown() + { + await Browser.GotoAsync("/input/scrollable.html"); + await Browser.Locator("body").TapAsync(); + await Browser.Keyboard.PressAsync("PageDown"); + await Expect.Poll(() => Browser.EvaluateAsync("scrollY > 0")).ToBeAsync(true); + } + + [Test] + public async Task Should_move_around_the_selection_in_a_contenteditable() + { + await Browser.GotoAsync(Content("
")); + await Browser.Locator("div").FocusAsync(); + var modifier = IsMac ? "Alt" : "Control"; + await Browser.Keyboard.TypeAsync("Hello World"); + await Browser.Keyboard.DownAsync(modifier); + await Browser.Keyboard.DownAsync("Shift"); + await Browser.Keyboard.PressAsync("ArrowLeft"); + await Browser.Keyboard.UpAsync("Shift"); + await Browser.Keyboard.UpAsync(modifier); + Assert.That(await Browser.EvaluateAsync("() => window.getSelection().toString()"), Is.EqualTo("World")); + } + + [Test] + public async Task Should_move_to_the_start_of_the_document() + { + Assume.That(IsMac, Is.True, "macOS only"); + await Browser.GotoAsync(Content("
")); + await Browser.Locator("div").FocusAsync(); + await Browser.Keyboard.TypeAsync("1\n2\n3\n"); + await Browser.Keyboard.PressAsync("Shift+Meta+ArrowUp"); + Assert.That(await Browser.EvaluateAsync("() => window.getSelection().toString()"), Is.EqualTo("1\n2\n3\n")); + } + + [Test] + public async Task Should_dispatch_a_click_event_on_a_button_when_Space_gets_pressed() + { + await Browser.GotoAsync(Content("")); + await Browser.EvaluateAsync("() => { window.actual = { clicked: false }; document.querySelector('button').addEventListener('click', () => (window.actual.clicked = true)); }"); + await Browser.Locator("button").FocusAsync(); + await Browser.Keyboard.PressAsync("Space"); + Assert.That(await Browser.EvaluateAsync("actual.clicked"), Is.True); + } + + [Test] + public async Task Should_dispatch_a_click_event_on_a_button_when_Enter_gets_pressed() + { + await Browser.GotoAsync(Content("")); + await Browser.EvaluateAsync("() => { window.actual = { clicked: false }; document.querySelector('button').addEventListener('click', () => (window.actual.clicked = true)); }"); + await Browser.Locator("button").FocusAsync(); + await Browser.Keyboard.PressAsync("Enter"); + Assert.That(await Browser.EvaluateAsync("actual.clicked"), Is.True); + } + + [Test] + public async Task Should_support_simple_copy_pasting() + { + await Browser.GotoAsync(Content("
123
")); + await Browser.Locator("div").FocusAsync(); + await Browser.Keyboard.PressAsync("ControlOrMeta+KeyA"); + await Browser.Keyboard.PressAsync("ControlOrMeta+KeyC"); + await Browser.Keyboard.PressAsync("ControlOrMeta+KeyV"); + await Browser.Keyboard.PressAsync("ControlOrMeta+KeyV"); + Assert.That(await Browser.EvaluateAsync("() => document.querySelector('div').textContent"), Is.EqualTo("123123")); + } + + [Test] + public async Task Should_support_simple_cut_pasting() + { + await Browser.GotoAsync(Content("
123
")); + await Browser.Locator("div").FocusAsync(); + await Browser.Keyboard.PressAsync("ControlOrMeta+KeyA"); + await Browser.Keyboard.PressAsync("ControlOrMeta+KeyX"); + await Browser.Keyboard.PressAsync("ControlOrMeta+KeyV"); + await Browser.Keyboard.PressAsync("ControlOrMeta+KeyV"); + Assert.That(await Browser.EvaluateAsync("() => document.querySelector('div').textContent"), Is.EqualTo("123123")); + } + + [Test] + public async Task Should_support_undo_redo() + { + await Browser.GotoAsync(Content("
")); + var div = Browser.Locator("div"); + await Expect.That(div).ToHaveTextAsync(""); + await div.PressSequentiallyAsync("123"); + await Expect.That(div).ToHaveTextAsync("123"); + await Browser.Keyboard.PressAsync("ControlOrMeta+KeyZ"); + await Expect.That(div).ToHaveTextAsync(""); + await Browser.Keyboard.PressAsync("Shift+ControlOrMeta+KeyZ"); + await Expect.That(div).ToHaveTextAsync("123"); + } + + /// A page with a shadow-element whose shadow root holds , for the typing-in-shadow-dom tests. + private static string ShadowElementPage(string editors) => $$""" + + + + + + + """; + + [Test] + public async Task Should_type_repeatedly_in_contenteditable_in_shadow_dom() + { + await Browser.GotoAsync(Content(ShadowElementPage(""" +
+
+
+
+
+ """))); + + var editor = Browser.Locator("shadow-element > .editor").First(); + await editor.PressSequentiallyAsync("This is the first box."); + + var sectionEditor = Browser.Locator("section .editor"); + await sectionEditor.PressSequentiallyAsync("This is the second box."); + + Assert.That(await editor.TextContentAsync(), Is.EqualTo("This is the first box.")); + Assert.That(await sectionEditor.TextContentAsync(), Is.EqualTo("This is the second box.")); + } + + [Test] + public async Task Should_type_repeatedly_in_contenteditable_in_shadow_dom_with_nested_elements() + { + await Browser.GotoAsync(Content(ShadowElementPage(""" +

hello

+
+
+

world

+
+ """))); + + var editor = Browser.Locator("shadow-element > .editor").First(); + await editor.PressSequentiallyAsync("This is the first box: "); + + var sectionEditor = Browser.Locator("section .editor"); + await sectionEditor.PressSequentiallyAsync("This is the second box: "); + + Assert.That(await editor.TextContentAsync(), Is.EqualTo("This is the first box: hello")); + Assert.That(await sectionEditor.TextContentAsync(), Is.EqualTo("This is the second box: world")); + } + + [Test] + public async Task Should_type_repeatedly_in_input_in_shadow_dom() + { + await Browser.GotoAsync(Content(ShadowElementPage(""" + +
+
+ +
+ """))); + + var editor = Browser.Locator("shadow-element > .editor").First(); + await editor.PressSequentiallyAsync("This is the first box."); + + var sectionEditor = Browser.Locator("section .editor"); + await sectionEditor.PressSequentiallyAsync("This is the second box."); + + Assert.That(await editor.InputValueAsync(), Is.EqualTo("This is the first box.")); + Assert.That(await sectionEditor.InputValueAsync(), Is.EqualTo("This is the second box.")); + } + + [Test] + public async Task Type_to_non_focusable_element_should_maintain_old_focus() + { + await Browser.GotoAsync(Content(""" +
focusable div
+
non-editable, non-focusable
+ """)); + + await Browser.Locator("#focusable").FocusAsync(); + Assert.That(await Browser.EvaluateAsync("() => document.activeElement?.id"), Is.EqualTo("focusable")); + await Browser.Locator("#non-focusable-and-non-editable").PressSequentiallyAsync("foo"); + Assert.That(await Browser.EvaluateAsync("() => document.activeElement?.id"), Is.EqualTo("focusable")); + } + + [Test] + public async Task Should_have_correct_Keydown_Keyup_order_when_pressing_Escape_key() + { + await Browser.GotoAsync("/input/keyboard.html"); + await Browser.Keyboard.PressAsync("Escape"); + Assert.That(await ResultAsync(), Is.EqualTo(Lines("Keydown: Escape Escape STANDARD []", "Keyup: Escape Escape STANDARD []"))); + } + + [Test] + public async Task Should_close_dialog_on_Escape_key_press_in_contenteditable() + { + await Browser.GotoAsync(Content(""" + +
Edit Me
+
+ """)); + var widget = Browser.Locator("dialog [contenteditable]"); + await Browser.EvaluateAsync("() => document.querySelector('dialog').showModal()"); + await Expect.Poll(() => Browser.EvaluateAsync("() => document.querySelector('dialog').open")).ToBeAsync(true); + await Expect.That(widget).ToBeVisibleAsync(); + + await widget.PressAsync("Escape"); + await Expect.Poll(() => Browser.EvaluateAsync("() => document.querySelector('dialog').open")).ToBeAsync(false); + await Expect.That(widget).Not.ToBeVisibleAsync(); + } + + private sealed record LastKeydown(string Key, string Code, bool MetaKey); +} diff --git a/tests/E2E.NUnit.Tests/Testbed/playwright/assets/input/keyboard.html b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/input/keyboard.html new file mode 100644 index 000000000..049ed439b --- /dev/null +++ b/tests/E2E.NUnit.Tests/Testbed/playwright/assets/input/keyboard.html @@ -0,0 +1,51 @@ + + + + Keyboard test + + + + + + \ No newline at end of file