diff --git a/.changeset/timeout-names-pattern.md b/.changeset/timeout-names-pattern.md new file mode 100644 index 0000000000..ba011f4470 --- /dev/null +++ b/.changeset/timeout-names-pattern.md @@ -0,0 +1,6 @@ +--- +"e2e": patch +"@e2e-dev/web": patch +--- + +A fixture call that times out names what it waited for: `browser.waitForResponse('foo.css')` fails with `operation timed out in browser.waitForResponse "foo.css"`. Steps for `waitForURL`, `waitForResponse`, `route`, and `unroute` show a string pattern in quotes and a RegExp as its literal. diff --git a/.fallowrc.json b/.fallowrc.json index 7751fab329..541d166fdf 100644 --- a/.fallowrc.json +++ b/.fallowrc.json @@ -35,6 +35,7 @@ "examples/**", "**/next-env.d.ts", "**/.e2e/**", + "apps/testbed/app/playwright/assets/**", "packages/e2e/tests/tmp-projects/**" ], "ignoreDependencies": [ diff --git a/.github/workflows/spec.yml b/.github/workflows/spec.yml index e374d7aff3..c8a755eb8b 100644 --- a/.github/workflows/spec.yml +++ b/.github/workflows/spec.yml @@ -66,12 +66,17 @@ jobs: - name: Install browsers run: pnpm --filter @e2e-dev/web exec playwright-core install chromium --with-deps --only-shell # On a pull request, Jev leaves out the tests the change can't affect; - # the merge queue and main pass no --changed-since and run every test. + # a push to main passes no --changed-since and runs every test. # Without the key (a fork's pull request), every test runs. - name: Testbed - run: pnpm --filter @e2e-dev/testbed test ${{ github.event_name == 'pull_request' && format('--changed-since origin/{0}', github.base_ref) || '' }} + run: pnpm --filter @e2e-dev/testbed test ${{ github.event_name == 'pull_request' && format('--changed-since origin/{0} --exclude-tag playwright', github.base_ref) || '' }} env: AI_GATEWAY_API_KEY: ${{ secrets.AI_GATEWAY_API_KEY }} + # The tests ported from Playwright pin the web engine's behavior, so a + # pull request runs all of them, not only the ones Jev picks. + - name: Testbed, Playwright tests + if: ${{ github.event_name == 'pull_request' }} + run: pnpm --filter @e2e-dev/testbed exec e2e run --tag playwright test: runs-on: blacksmith-4vcpu-ubuntu-2404 diff --git a/.oxlintrc.json b/.oxlintrc.json index e257a33c61..0ece7fe2f6 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -16,6 +16,8 @@ "packages/*/tests/fixtures/**", // Vendored conformance data, kept byte for byte. "packages/*/tests/conformance/*/**", + // Playwright's test assets, kept byte for byte. + "apps/testbed/app/playwright/assets/**", "packages/*/tests/tmp-projects/**", // Standalone user-facing projects with their own installs; nothing here builds them. "examples/**", diff --git a/apps/testbed/.gitignore b/apps/testbed/.gitignore index 0daf3d8941..d8320ed41d 100644 --- a/apps/testbed/.gitignore +++ b/apps/testbed/.gitignore @@ -14,3 +14,5 @@ # Verification skill scratch: bug-bash charter output and proofs kept past the next run. .e2e/bugbash/ .e2e/proof/ +# Goldens the Playwright screenshot tests write while they run. +tests/screenshot.e2e.ts-snapshots/ diff --git a/apps/testbed/README.md b/apps/testbed/README.md index ff3dbbfd2d..1104a2011f 100644 --- a/apps/testbed/README.md +++ b/apps/testbed/README.md @@ -17,6 +17,9 @@ here. `controls` (control states, scrolling, the browser fixture's page, the speed counter, about). `app/pages/index.mjs` merges them and `app/layout.mjs` renders the nav from that registry. +- `app/playwright/`: Playwright's test assets (v1.64.1, Apache-2.0, with its + `LICENSE` and `NOTICE`) and the dynamic routes its test server sets, served + by the playground for any path it has no page for. - `app/bug-garden.mjs` — a bookshop with planted defects, for `e2e explore`. - `dogfood/server.mjs` — an expense-claims app with a test API, for the executor dogfoods. @@ -27,7 +30,14 @@ here. states and the failure codes (`controls`), pointer coordinates and path swipes (`pointer`), viewport and node scrolling (`scroll`), the `browser` fixture's own verbs (`browser`), and the per-action speed floor (`speed`). - `tests/helpers.ts` holds the shared `failure`, `boxOf`, and `centerOf`. + The files tagged `playwright` are Playwright's own `tests/page` specs (and + `tests/library/download.spec.ts`) at v1.64.1, ported to the public API: + each header names its source and the tests left out. `fail: 'reason'` + marks a known difference from Playwright; `skip: 'reason'` one that fails + with an error `fail` does not cover. `--tag playwright` runs only them, and + CI runs them on every pull request. + `tests/helpers.ts` holds the shared `failure`, `boxOf`, and `centerOf`, + and the ported tests' `content`, `asset`, `PREFIX`, and `CROSS`. - `e2e.lightpanda.config.ts` and `e2e.lightpanda-agent.config.ts`: the local suite and the agent suite on `@e2e-dev/lightpanda`, which starts [Lightpanda](https://lightpanda.io) from `LIGHTPANDA_PATH` (or `PATH`), diff --git a/apps/testbed/app/playwright/LICENSE b/apps/testbed/app/playwright/LICENSE new file mode 100644 index 0000000000..4ace03ddb6 --- /dev/null +++ b/apps/testbed/app/playwright/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Portions Copyright (c) Microsoft Corporation. + Portions Copyright 2017 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/apps/testbed/app/playwright/NOTICE b/apps/testbed/app/playwright/NOTICE new file mode 100644 index 0000000000..814ec1696f --- /dev/null +++ b/apps/testbed/app/playwright/NOTICE @@ -0,0 +1,5 @@ +Playwright +Copyright (c) Microsoft Corporation + +This software contains code derived from the Puppeteer project (https://github.com/puppeteer/puppeteer), +available under the Apache 2.0 license (https://github.com/puppeteer/puppeteer/blob/master/LICENSE). diff --git a/apps/testbed/app/playwright/assets/button-overlay-oopif.html b/apps/testbed/app/playwright/assets/button-overlay-oopif.html new file mode 100644 index 0000000000..7e1f136fcd --- /dev/null +++ b/apps/testbed/app/playwright/assets/button-overlay-oopif.html @@ -0,0 +1,39 @@ + + diff --git a/apps/testbed/app/playwright/assets/chromium-linux.zip b/apps/testbed/app/playwright/assets/chromium-linux.zip new file mode 100644 index 0000000000..9c00ec080d Binary files /dev/null and b/apps/testbed/app/playwright/assets/chromium-linux.zip differ diff --git a/apps/testbed/app/playwright/assets/consolelog.html b/apps/testbed/app/playwright/assets/consolelog.html new file mode 100644 index 0000000000..9ef271812d --- /dev/null +++ b/apps/testbed/app/playwright/assets/consolelog.html @@ -0,0 +1,11 @@ + + + + console.log test + + + + + diff --git a/apps/testbed/app/playwright/assets/counter.html b/apps/testbed/app/playwright/assets/counter.html new file mode 100644 index 0000000000..1e90289577 --- /dev/null +++ b/apps/testbed/app/playwright/assets/counter.html @@ -0,0 +1,10 @@ + + +

count: 0

+ diff --git a/apps/testbed/app/playwright/assets/css-transition.html b/apps/testbed/app/playwright/assets/css-transition.html new file mode 100644 index 0000000000..449c1548df --- /dev/null +++ b/apps/testbed/app/playwright/assets/css-transition.html @@ -0,0 +1,21 @@ + + +
+ diff --git a/apps/testbed/app/playwright/assets/digits/0.png b/apps/testbed/app/playwright/assets/digits/0.png new file mode 100644 index 0000000000..ac3c4768ed Binary files /dev/null and b/apps/testbed/app/playwright/assets/digits/0.png differ diff --git a/apps/testbed/app/playwright/assets/digits/1.png b/apps/testbed/app/playwright/assets/digits/1.png new file mode 100644 index 0000000000..6768222729 Binary files /dev/null and b/apps/testbed/app/playwright/assets/digits/1.png differ diff --git a/apps/testbed/app/playwright/assets/digits/2.png b/apps/testbed/app/playwright/assets/digits/2.png new file mode 100644 index 0000000000..b1daa4735d Binary files /dev/null and b/apps/testbed/app/playwright/assets/digits/2.png differ diff --git a/apps/testbed/app/playwright/assets/digits/3.png b/apps/testbed/app/playwright/assets/digits/3.png new file mode 100644 index 0000000000..6eca99b21b Binary files /dev/null and b/apps/testbed/app/playwright/assets/digits/3.png differ diff --git a/apps/testbed/app/playwright/assets/digits/4.png b/apps/testbed/app/playwright/assets/digits/4.png new file mode 100644 index 0000000000..a721071e2c Binary files /dev/null and b/apps/testbed/app/playwright/assets/digits/4.png differ diff --git a/apps/testbed/app/playwright/assets/digits/5.png b/apps/testbed/app/playwright/assets/digits/5.png new file mode 100644 index 0000000000..15cb19932a Binary files /dev/null and b/apps/testbed/app/playwright/assets/digits/5.png differ diff --git a/apps/testbed/app/playwright/assets/digits/6.png b/apps/testbed/app/playwright/assets/digits/6.png new file mode 100644 index 0000000000..639f38439d Binary files /dev/null and b/apps/testbed/app/playwright/assets/digits/6.png differ diff --git a/apps/testbed/app/playwright/assets/digits/7.png b/apps/testbed/app/playwright/assets/digits/7.png new file mode 100644 index 0000000000..5c1150b005 Binary files /dev/null and b/apps/testbed/app/playwright/assets/digits/7.png differ diff --git a/apps/testbed/app/playwright/assets/digits/8.png b/apps/testbed/app/playwright/assets/digits/8.png new file mode 100644 index 0000000000..abb8b48b0b Binary files /dev/null and b/apps/testbed/app/playwright/assets/digits/8.png differ diff --git a/apps/testbed/app/playwright/assets/digits/9.png b/apps/testbed/app/playwright/assets/digits/9.png new file mode 100644 index 0000000000..6a40a21c6f Binary files /dev/null and b/apps/testbed/app/playwright/assets/digits/9.png differ diff --git a/apps/testbed/app/playwright/assets/dom.html b/apps/testbed/app/playwright/assets/dom.html new file mode 100644 index 0000000000..25572912e7 --- /dev/null +++ b/apps/testbed/app/playwright/assets/dom.html @@ -0,0 +1,5 @@ +
Text, +more text
+ + + diff --git a/apps/testbed/app/playwright/assets/download-blob.html b/apps/testbed/app/playwright/assets/download-blob.html new file mode 100644 index 0000000000..3c4a3d8133 --- /dev/null +++ b/apps/testbed/app/playwright/assets/download-blob.html @@ -0,0 +1,29 @@ + + + + Blob Download Example + + + + Download + + diff --git a/apps/testbed/app/playwright/assets/empty.html b/apps/testbed/app/playwright/assets/empty.html new file mode 100644 index 0000000000..e69de29bb2 diff --git a/apps/testbed/app/playwright/assets/empty.pdf b/apps/testbed/app/playwright/assets/empty.pdf new file mode 100644 index 0000000000..ed845a6372 Binary files /dev/null and b/apps/testbed/app/playwright/assets/empty.pdf differ diff --git a/apps/testbed/app/playwright/assets/file to upload.txt b/apps/testbed/app/playwright/assets/file to upload.txt new file mode 100644 index 0000000000..b4ad118489 --- /dev/null +++ b/apps/testbed/app/playwright/assets/file to upload.txt @@ -0,0 +1 @@ +contents of the file \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/file-to-upload-2.txt b/apps/testbed/app/playwright/assets/file-to-upload-2.txt new file mode 100644 index 0000000000..b4ad118489 --- /dev/null +++ b/apps/testbed/app/playwright/assets/file-to-upload-2.txt @@ -0,0 +1 @@ +contents of the file \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/file-to-upload.txt b/apps/testbed/app/playwright/assets/file-to-upload.txt new file mode 100644 index 0000000000..b4ad118489 --- /dev/null +++ b/apps/testbed/app/playwright/assets/file-to-upload.txt @@ -0,0 +1 @@ +contents of the file \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/frames/child-redirect.html b/apps/testbed/app/playwright/assets/frames/child-redirect.html new file mode 100644 index 0000000000..d4806e7f6b --- /dev/null +++ b/apps/testbed/app/playwright/assets/frames/child-redirect.html @@ -0,0 +1 @@ + diff --git a/apps/testbed/app/playwright/assets/frames/frame.html b/apps/testbed/app/playwright/assets/frames/frame.html new file mode 100644 index 0000000000..3d3b943431 --- /dev/null +++ b/apps/testbed/app/playwright/assets/frames/frame.html @@ -0,0 +1,19 @@ + + + + + +
Hi, I'm frame
diff --git a/apps/testbed/app/playwright/assets/frames/frameset.html b/apps/testbed/app/playwright/assets/frames/frameset.html new file mode 100644 index 0000000000..4d56f88839 --- /dev/null +++ b/apps/testbed/app/playwright/assets/frames/frameset.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/apps/testbed/app/playwright/assets/frames/lazy-frame.html b/apps/testbed/app/playwright/assets/frames/lazy-frame.html new file mode 100644 index 0000000000..f5e0e0914d --- /dev/null +++ b/apps/testbed/app/playwright/assets/frames/lazy-frame.html @@ -0,0 +1,6 @@ +
One
+
Two
+
Three
+
Four
+
Five
+ diff --git a/apps/testbed/app/playwright/assets/frames/nested-frames.html b/apps/testbed/app/playwright/assets/frames/nested-frames.html new file mode 100644 index 0000000000..d858d3285b --- /dev/null +++ b/apps/testbed/app/playwright/assets/frames/nested-frames.html @@ -0,0 +1,30 @@ + + + + diff --git a/apps/testbed/app/playwright/assets/frames/one-frame.html b/apps/testbed/app/playwright/assets/frames/one-frame.html new file mode 100644 index 0000000000..e941d795a2 --- /dev/null +++ b/apps/testbed/app/playwright/assets/frames/one-frame.html @@ -0,0 +1 @@ + diff --git a/apps/testbed/app/playwright/assets/frames/redirect-my-parent.html b/apps/testbed/app/playwright/assets/frames/redirect-my-parent.html new file mode 100644 index 0000000000..3beb0aac1a --- /dev/null +++ b/apps/testbed/app/playwright/assets/frames/redirect-my-parent.html @@ -0,0 +1,3 @@ + diff --git a/apps/testbed/app/playwright/assets/frames/script.js b/apps/testbed/app/playwright/assets/frames/script.js new file mode 100644 index 0000000000..be22256d16 --- /dev/null +++ b/apps/testbed/app/playwright/assets/frames/script.js @@ -0,0 +1 @@ +console.log('Cheers!'); diff --git a/apps/testbed/app/playwright/assets/frames/style.css b/apps/testbed/app/playwright/assets/frames/style.css new file mode 100644 index 0000000000..5b5436e874 --- /dev/null +++ b/apps/testbed/app/playwright/assets/frames/style.css @@ -0,0 +1,3 @@ +div { + color: blue; +} diff --git a/apps/testbed/app/playwright/assets/frames/two-frames.html b/apps/testbed/app/playwright/assets/frames/two-frames.html new file mode 100644 index 0000000000..00324f0845 --- /dev/null +++ b/apps/testbed/app/playwright/assets/frames/two-frames.html @@ -0,0 +1,16 @@ + + + diff --git a/apps/testbed/app/playwright/assets/global-var.html b/apps/testbed/app/playwright/assets/global-var.html new file mode 100644 index 0000000000..b6be975038 --- /dev/null +++ b/apps/testbed/app/playwright/assets/global-var.html @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/grid-iframe-in-shadow.html b/apps/testbed/app/playwright/assets/grid-iframe-in-shadow.html new file mode 100644 index 0000000000..4649b27227 --- /dev/null +++ b/apps/testbed/app/playwright/assets/grid-iframe-in-shadow.html @@ -0,0 +1,16 @@ + + diff --git a/apps/testbed/app/playwright/assets/grid.html b/apps/testbed/app/playwright/assets/grid.html new file mode 100644 index 0000000000..8345f429bd --- /dev/null +++ b/apps/testbed/app/playwright/assets/grid.html @@ -0,0 +1,66 @@ + + + diff --git a/apps/testbed/app/playwright/assets/historyapi.html b/apps/testbed/app/playwright/assets/historyapi.html new file mode 100644 index 0000000000..bacaf9e9a0 --- /dev/null +++ b/apps/testbed/app/playwright/assets/historyapi.html @@ -0,0 +1,5 @@ + diff --git a/apps/testbed/app/playwright/assets/injectedstyle.css b/apps/testbed/app/playwright/assets/injectedstyle.css new file mode 100644 index 0000000000..aa1634c255 --- /dev/null +++ b/apps/testbed/app/playwright/assets/injectedstyle.css @@ -0,0 +1,3 @@ +body { + background-color: red; +} diff --git a/apps/testbed/app/playwright/assets/input/animating-button.html b/apps/testbed/app/playwright/assets/input/animating-button.html new file mode 100644 index 0000000000..2946f2e89f --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/animating-button.html @@ -0,0 +1,42 @@ + + diff --git a/apps/testbed/app/playwright/assets/input/background-fixed.html b/apps/testbed/app/playwright/assets/input/background-fixed.html new file mode 100644 index 0000000000..5093939a5b --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/background-fixed.html @@ -0,0 +1,16 @@ + + + + + +
tall
+ + diff --git a/apps/testbed/app/playwright/assets/input/button.html b/apps/testbed/app/playwright/assets/input/button.html new file mode 100644 index 0000000000..bfce25ee00 --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/button.html @@ -0,0 +1,32 @@ + + + + Button test + + + + + + + \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/input/checkbox.html b/apps/testbed/app/playwright/assets/input/checkbox.html new file mode 100644 index 0000000000..ca56762e2b --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/checkbox.html @@ -0,0 +1,42 @@ + + + + Selection Test + + + + + + + diff --git a/apps/testbed/app/playwright/assets/input/drag-n-drop-manual.html b/apps/testbed/app/playwright/assets/input/drag-n-drop-manual.html new file mode 100644 index 0000000000..ee67aeb4d6 --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/drag-n-drop-manual.html @@ -0,0 +1,44 @@ + + +
+
+ Drop here +
+
+ Drag me +
+
+ + diff --git a/apps/testbed/app/playwright/assets/input/fileupload-multi.html b/apps/testbed/app/playwright/assets/input/fileupload-multi.html new file mode 100644 index 0000000000..05dd5a2237 --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/fileupload-multi.html @@ -0,0 +1,12 @@ + + + + File upload test + + +
+ + +
+ + diff --git a/apps/testbed/app/playwright/assets/input/fileupload.html b/apps/testbed/app/playwright/assets/input/fileupload.html new file mode 100644 index 0000000000..6486e5c288 --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/fileupload.html @@ -0,0 +1,12 @@ + + + + File upload test + + +
+ + +
+ + \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/input/folderupload.html b/apps/testbed/app/playwright/assets/input/folderupload.html new file mode 100644 index 0000000000..16c7e2c3e9 --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/folderupload.html @@ -0,0 +1,12 @@ + + + + Folder upload test + + +
+ + +
+ + \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/input/handle-locator.html b/apps/testbed/app/playwright/assets/input/handle-locator.html new file mode 100644 index 0000000000..5b164d5c7a --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/handle-locator.html @@ -0,0 +1,91 @@ + + + + Interstitial test + + + +
+
A place on the side to hover
+
+
This interstitial covers the button
+ +
+ + + diff --git a/apps/testbed/app/playwright/assets/input/keyboard.html b/apps/testbed/app/playwright/assets/input/keyboard.html new file mode 100644 index 0000000000..049ed439be --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/keyboard.html @@ -0,0 +1,51 @@ + + + + Keyboard test + + + + + + \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/input/mouse-helper.js b/apps/testbed/app/playwright/assets/input/mouse-helper.js new file mode 100644 index 0000000000..3c4d57033c --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/mouse-helper.js @@ -0,0 +1,62 @@ +// This injects a box into the page that moves with the mouse; +// Useful for debugging +(function(){ + const box = document.createElement('div'); + box.classList.add('mouse-helper'); + const styleElement = document.createElement('style'); + styleElement.innerHTML = ` + .mouse-helper { + pointer-events: none; + position: absolute; + top: 0; + left: 0; + width: 20px; + height: 20px; + background: rgba(0,0,0,.4); + border: 1px solid white; + border-radius: 10px; + margin-left: -10px; + margin-top: -10px; + transition: background .2s, border-radius .2s, border-color .2s; + } + .mouse-helper.button-1 { + transition: none; + background: rgba(0,0,0,0.9); + } + .mouse-helper.button-2 { + transition: none; + border-color: rgba(0,0,255,0.9); + } + .mouse-helper.button-3 { + transition: none; + border-radius: 4px; + } + .mouse-helper.button-4 { + transition: none; + border-color: rgba(255,0,0,0.9); + } + .mouse-helper.button-5 { + transition: none; + border-color: rgba(0,255,0,0.9); + } + `; + document.head.appendChild(styleElement); + document.body.appendChild(box); + document.addEventListener('mousemove', event => { + box.style.left = event.pageX + 'px'; + box.style.top = event.pageY + 'px'; + updateButtons(event.buttons); + }, true); + document.addEventListener('mousedown', event => { + updateButtons(event.buttons); + box.classList.add('button-' + event.which); + }, true); + document.addEventListener('mouseup', event => { + updateButtons(event.buttons); + box.classList.remove('button-' + event.which); + }, true); + function updateButtons(buttons) { + for (let i = 0; i < 5; i++) + box.classList.toggle('button-' + i, buttons & (1 << i)); + } +})(); diff --git a/apps/testbed/app/playwright/assets/input/rotatedButton.html b/apps/testbed/app/playwright/assets/input/rotatedButton.html new file mode 100644 index 0000000000..1bce66cf5e --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/rotatedButton.html @@ -0,0 +1,21 @@ + + + + Rotated button test + + + + + + + + diff --git a/apps/testbed/app/playwright/assets/input/scrollable.html b/apps/testbed/app/playwright/assets/input/scrollable.html new file mode 100644 index 0000000000..885d3739d5 --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/scrollable.html @@ -0,0 +1,23 @@ + + + + Scrollable test + + + + + + \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/input/scrollable2.html b/apps/testbed/app/playwright/assets/input/scrollable2.html new file mode 100644 index 0000000000..885d3739d5 --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/scrollable2.html @@ -0,0 +1,23 @@ + + + + Scrollable test + + + + + + \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/input/select.html b/apps/testbed/app/playwright/assets/input/select.html new file mode 100644 index 0000000000..42784c28f3 --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/select.html @@ -0,0 +1,70 @@ + + + + Selection Test + + + + + + diff --git a/apps/testbed/app/playwright/assets/input/textarea.html b/apps/testbed/app/playwright/assets/input/textarea.html new file mode 100644 index 0000000000..11da79882e --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/textarea.html @@ -0,0 +1,20 @@ + + + + Textarea test + + + + +
+
Plain div
+ + + + \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/input/touches.html b/apps/testbed/app/playwright/assets/input/touches.html new file mode 100644 index 0000000000..4392cfacbd --- /dev/null +++ b/apps/testbed/app/playwright/assets/input/touches.html @@ -0,0 +1,35 @@ + + + + Touch test + + + + + + + \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/networkidle-frame.html b/apps/testbed/app/playwright/assets/networkidle-frame.html new file mode 100644 index 0000000000..3bf7ad4feb --- /dev/null +++ b/apps/testbed/app/playwright/assets/networkidle-frame.html @@ -0,0 +1 @@ + diff --git a/apps/testbed/app/playwright/assets/networkidle.html b/apps/testbed/app/playwright/assets/networkidle.html new file mode 100644 index 0000000000..ab10c97967 --- /dev/null +++ b/apps/testbed/app/playwright/assets/networkidle.html @@ -0,0 +1 @@ + diff --git a/apps/testbed/app/playwright/assets/networkidle.js b/apps/testbed/app/playwright/assets/networkidle.js new file mode 100644 index 0000000000..9d8998458a --- /dev/null +++ b/apps/testbed/app/playwright/assets/networkidle.js @@ -0,0 +1,12 @@ +async function main() { + window.ws = new WebSocket('ws://localhost:' + window.location.port + '/ws'); + window.ws.addEventListener('message', message => {}); + + fetch('fetch-request-a.js'); + window.top.fetchSecond = () => { + // Do not return the promise here. + fetch('fetch-request-b.js'); + }; +} + +main(); diff --git a/apps/testbed/app/playwright/assets/offscreenbuttons.html b/apps/testbed/app/playwright/assets/offscreenbuttons.html new file mode 100644 index 0000000000..b7f381decd --- /dev/null +++ b/apps/testbed/app/playwright/assets/offscreenbuttons.html @@ -0,0 +1,55 @@ + +
+ + + + + + + + + + + +
+ diff --git a/apps/testbed/app/playwright/assets/one-style.css b/apps/testbed/app/playwright/assets/one-style.css new file mode 100644 index 0000000000..7b26410d8a --- /dev/null +++ b/apps/testbed/app/playwright/assets/one-style.css @@ -0,0 +1,3 @@ +body { + background-color: pink; +} diff --git a/apps/testbed/app/playwright/assets/one-style.html b/apps/testbed/app/playwright/assets/one-style.html new file mode 100644 index 0000000000..b3a6eeeebe --- /dev/null +++ b/apps/testbed/app/playwright/assets/one-style.html @@ -0,0 +1,3 @@ + + +
hello, world!
diff --git a/apps/testbed/app/playwright/assets/playground.html b/apps/testbed/app/playwright/assets/playground.html new file mode 100644 index 0000000000..828cfb1c70 --- /dev/null +++ b/apps/testbed/app/playwright/assets/playground.html @@ -0,0 +1,15 @@ + + + + Playground + + + + +
First div
+
+ Second div + Inner span +
+ + \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/pptr.png b/apps/testbed/app/playwright/assets/pptr.png new file mode 100644 index 0000000000..65d87c68e6 Binary files /dev/null and b/apps/testbed/app/playwright/assets/pptr.png differ diff --git a/apps/testbed/app/playwright/assets/preload.html b/apps/testbed/app/playwright/assets/preload.html new file mode 100644 index 0000000000..dc10ff6d69 --- /dev/null +++ b/apps/testbed/app/playwright/assets/preload.html @@ -0,0 +1,5 @@ + + +
hello, world!
diff --git a/apps/testbed/app/playwright/assets/redirectloop1.html b/apps/testbed/app/playwright/assets/redirectloop1.html new file mode 100644 index 0000000000..d542c4e9e4 --- /dev/null +++ b/apps/testbed/app/playwright/assets/redirectloop1.html @@ -0,0 +1,10 @@ +> diff --git a/apps/testbed/app/playwright/assets/redirectloop2.html b/apps/testbed/app/playwright/assets/redirectloop2.html new file mode 100644 index 0000000000..87c7194798 --- /dev/null +++ b/apps/testbed/app/playwright/assets/redirectloop2.html @@ -0,0 +1,5 @@ + diff --git a/apps/testbed/app/playwright/assets/rotate-pseudo.html b/apps/testbed/app/playwright/assets/rotate-pseudo.html new file mode 100644 index 0000000000..dca33ecdea --- /dev/null +++ b/apps/testbed/app/playwright/assets/rotate-pseudo.html @@ -0,0 +1,32 @@ + + + + + +
+ + diff --git a/apps/testbed/app/playwright/assets/rotate-z-shadow-dom.html b/apps/testbed/app/playwright/assets/rotate-z-shadow-dom.html new file mode 100644 index 0000000000..0a6e3f723e --- /dev/null +++ b/apps/testbed/app/playwright/assets/rotate-z-shadow-dom.html @@ -0,0 +1,31 @@ + + + + + diff --git a/apps/testbed/app/playwright/assets/rotate-z.html b/apps/testbed/app/playwright/assets/rotate-z.html new file mode 100644 index 0000000000..5397789419 --- /dev/null +++ b/apps/testbed/app/playwright/assets/rotate-z.html @@ -0,0 +1,26 @@ + + + + + +
+ + diff --git a/apps/testbed/app/playwright/assets/screenshots/canvas.html b/apps/testbed/app/playwright/assets/screenshots/canvas.html new file mode 100644 index 0000000000..a0ebc55829 --- /dev/null +++ b/apps/testbed/app/playwright/assets/screenshots/canvas.html @@ -0,0 +1,13 @@ + + + + diff --git a/apps/testbed/app/playwright/assets/screenshots/translateZ.html b/apps/testbed/app/playwright/assets/screenshots/translateZ.html new file mode 100644 index 0000000000..2b4aae8c09 --- /dev/null +++ b/apps/testbed/app/playwright/assets/screenshots/translateZ.html @@ -0,0 +1,4 @@ +
+
+
+
\ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/sectionselectorengine.js b/apps/testbed/app/playwright/assets/sectionselectorengine.js new file mode 100644 index 0000000000..e83b187a95 --- /dev/null +++ b/apps/testbed/app/playwright/assets/sectionselectorengine.js @@ -0,0 +1,8 @@ +({ + query(root, selector) { + return root.querySelector('section'); + }, + queryAll(root, selector) { + return Array.from(root.querySelectorAll('section')); + } +}) \ No newline at end of file diff --git a/apps/testbed/app/playwright/assets/self-request.html b/apps/testbed/app/playwright/assets/self-request.html new file mode 100644 index 0000000000..88aff620ff --- /dev/null +++ b/apps/testbed/app/playwright/assets/self-request.html @@ -0,0 +1,5 @@ + diff --git a/apps/testbed/app/playwright/assets/shadow.html b/apps/testbed/app/playwright/assets/shadow.html new file mode 100644 index 0000000000..d1fd331eb2 --- /dev/null +++ b/apps/testbed/app/playwright/assets/shadow.html @@ -0,0 +1,17 @@ + diff --git a/apps/testbed/app/playwright/assets/simple.json b/apps/testbed/app/playwright/assets/simple.json new file mode 100644 index 0000000000..6d95903051 --- /dev/null +++ b/apps/testbed/app/playwright/assets/simple.json @@ -0,0 +1 @@ +{"foo": "bar"} diff --git a/apps/testbed/app/playwright/assets/title.html b/apps/testbed/app/playwright/assets/title.html new file mode 100644 index 0000000000..6e81f4091a --- /dev/null +++ b/apps/testbed/app/playwright/assets/title.html @@ -0,0 +1,2 @@ + +Woof-Woof diff --git a/apps/testbed/app/playwright/assets/wrappedlink.html b/apps/testbed/app/playwright/assets/wrappedlink.html new file mode 100644 index 0000000000..429b6e9156 --- /dev/null +++ b/apps/testbed/app/playwright/assets/wrappedlink.html @@ -0,0 +1,32 @@ + +
+ 123321 +
+ diff --git a/apps/testbed/app/playwright/routes.mjs b/apps/testbed/app/playwright/routes.mjs new file mode 100644 index 0000000000..e0506ca3d3 --- /dev/null +++ b/apps/testbed/app/playwright/routes.mjs @@ -0,0 +1,225 @@ +/** + * The routes of the tests ported from Playwright: its test assets (`assets/`, + * copied from microsoft/playwright `tests/assets` at v1.64.1, Apache-2.0) plus + * the few dynamic routes Playwright's test server sets per test, fixed here as + * paths. `127.0.0.1` and `localhost` on the app's port are the two origins of + * the cross-origin cases, and the only ones trusted. + */ + +import { createHash } from 'node:crypto'; +import { createReadStream, existsSync, statSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), 'assets'); +const MAX_DELAY_MS = 30_000; +const MAX_BYTES = 16 << 20; +const TYPES = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.pdf': 'application/pdf', '.svg': 'image/svg+xml', '.txt': 'text/plain' }; + +/** The Playwright routes of the app on `port`: a request handler and a WebSocket upgrade handler. */ +export function playwrightRoutes(port) { + const ORIGINS = new Set([`http://127.0.0.1:${port}`, `http://localhost:${port}`]); + + /** `value` as a number in [0, max], `fallback` when absent. */ + function bounded(value, fallback, max) { + return Math.min(Math.max(Number(value ?? fallback) || 0, 0), max); + } + + /** A redirect target on this server (a path, or either origin), else the empty page. */ + function sameServer(target) { + if (target === null) return '/empty.html'; + const resolved = URL.canParse(target, `http://127.0.0.1:${port}`) ? new URL(target, `http://127.0.0.1:${port}`) : undefined; + if (resolved === undefined || !ORIGINS.has(resolved.origin)) return '/empty.html'; + return target.startsWith('/') ? `${resolved.pathname}${resolved.search}${resolved.hash}` : resolved.href; + } + + /** + * The request's origin when it is one of the server's own, the only ones + * granted credentials, or `null`, the origin a cross-origin redirect leaves. + */ + function trustedOrigin(request) { + const { origin } = request.headers; + if (origin === 'null') return 'null'; + return origin !== undefined && ORIGINS.has(origin) ? origin : `http://127.0.0.1:${port}`; + } + + /** The request body, read whole. */ + function body(request) { + return new Promise((resolve) => { + const chunks = []; + request.on('data', (chunk) => chunks.push(chunk)); + request.on('end', () => resolve(Buffer.concat(chunks))); + }); + } + + const counts = new Map(); + const logs = new Map(); + + /** Serves one request: a dynamic route, else an asset, else a 404. */ + async function handle(request, response) { + const url = new URL(request.url, 'http://localhost'); + const query = url.searchParams; + switch (url.pathname) { + case '/content': + response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); + response.end(Buffer.from(query.get('html') ?? '', 'base64url')); + return; + case '/echo': { + const received = await body(request); + response.writeHead(200, { 'content-type': 'application/json', 'access-control-allow-origin': '*' }); + response.end(JSON.stringify({ method: request.method, headers: request.headers, body: received.toString(), url: request.url })); + return; + } + case '/status': + response.writeHead(Number(query.get('code') ?? 200), { 'content-type': 'text/plain' }); + response.end(query.get('body') ?? ''); + return; + case '/slow': + setTimeout(() => { + response.writeHead(200, { 'content-type': query.get('type') ?? 'text/plain', 'access-control-allow-origin': '*' }); + response.end(query.get('body') ?? 'slow'); + }, bounded(query.get('ms'), 1000, MAX_DELAY_MS)); + return; + case '/never': + request.on('close', () => response.destroy()); + return; + case '/redirect': + response.writeHead(302, { location: sameServer(query.get('to')) }); + response.end(); + return; + case '/download': + response.writeHead(200, { + 'content-type': 'application/octet-stream', + 'content-disposition': `attachment${query.has('name') ? `; filename=${query.get('name')}` : ''}`, + }); + response.end(query.get('body') ?? 'Hello world'); + return; + case '/set-cookie': + response.writeHead(200, { 'set-cookie': query.get('cookie') ?? 'name=value', 'content-type': 'text/html' }); + response.end('cookie'); + return; + case '/respond': + response.writeHead(Number(query.get('status') ?? 200), JSON.parse(query.get('headers') ?? '{}')); + response.end(query.get('body') ?? ''); + return; + case '/cors-echo': { + const allow = { + 'access-control-allow-origin': trustedOrigin(request), + 'access-control-allow-credentials': 'true', + 'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE', + 'access-control-allow-headers': request.headers['access-control-request-headers'] ?? '*', + }; + if (request.method === 'OPTIONS' && query.has('preflight')) { + response.writeHead(204, allow); + response.end(); + return; + } + const received = await body(request); + response.writeHead(200, { 'content-type': 'text/plain', ...allow }); + response.end(JSON.stringify({ method: request.method, headers: request.headers, body: received.toString(), url: request.url })); + return; + } + case '/bounce': { + const headers = { + location: sameServer(query.get('to')), + 'access-control-allow-origin': trustedOrigin(request), + 'access-control-allow-credentials': 'true', + 'access-control-allow-headers': request.headers['access-control-request-headers'] ?? '*', + ...(query.has('cookie') ? { 'set-cookie': query.get('cookie') } : {}), + }; + if (request.method === 'OPTIONS') delete headers.location; + response.writeHead(request.method === 'OPTIONS' ? 204 : Number(query.get('status') ?? 302), headers); + response.end(); + return; + } + case '/count': { + const key = query.get('key') ?? ''; + counts.set(key, (counts.get(key) ?? 0) + 1); + response.writeHead(200, { 'content-type': 'text/plain' }); + response.end(String(counts.get(key) * 11)); + return; + } + case '/options': { + const key = query.get('key') ?? ''; + logs.set(key, [...(logs.get(key) ?? []), `${request.method}:${url.pathname}`]); + response.writeHead(200, request.method === 'OPTIONS' + ? { 'access-control-allow-origin': '*', 'access-control-allow-methods': 'POST, GET, OPTIONS, DELETE', 'access-control-allow-headers': '*', 'cache-control': 'no-cache' } + : { 'access-control-allow-origin': '*' }); + response.end(request.method === 'OPTIONS' ? 'Hello' : 'World'); + return; + } + case '/options-log': + response.writeHead(200, { 'content-type': 'application/json' }); + response.end(JSON.stringify(logs.get(query.get('key') ?? '') ?? [])); + return; + case '/upload': { + const received = await body(request); + const type = request.headers['content-type'] ?? ''; + const boundary = Buffer.from(`--${type.includes('boundary=') ? type.slice(type.indexOf('boundary=') + 'boundary='.length) : ''}`); + const files = []; + for (let start = received.indexOf(boundary); start !== -1;) { + const next = received.indexOf(boundary, start + boundary.length); + if (next === -1) break; + const part = received.subarray(start + boundary.length + 2, next - 2); + const split = part.indexOf('\r\n\r\n'); + const head = part.subarray(0, split).toString(); + const data = part.subarray(split + 4); + files.push({ + name: /name="([^"]*)"/.exec(head)?.[1], + filename: /filename="([^"]*)"/.exec(head)?.[1], + mimetype: /content-type: (.+)/i.exec(head)?.[1], + size: data.length, + base64: data.length <= 65536 ? data.toString('base64') : undefined, + }); + start = next; + } + response.writeHead(200, { 'content-type': 'text/plain', 'access-control-allow-origin': '*' }); + response.end(JSON.stringify(files)); + return; + } + case '/binary': { + const data = Buffer.alloc(bounded(query.get('bytes'), 1 << 20, MAX_BYTES)); + for (let i = 0; i < data.length; i++) data[i] = Math.imul(i + 1, 2654435761) >>> 24; + response.writeHead(200, { 'content-type': 'application/zip', 'content-length': data.length }); + response.end(data); + return; + } + case '/download-stall': + response.writeHead(200, { 'content-type': 'application/octet-stream', 'content-disposition': 'attachment; filename=file.txt' }); + response.write('a'.repeat(4096)); + response.write('foo'); + request.on('close', () => response.destroy()); + return; + case '/sse': + response.writeHead(200, { 'content-type': 'text/event-stream', connection: 'keep-alive', 'cache-control': 'no-cache' }); + response.write('data: hello\n\n'); + request.on('close', () => response.destroy()); + return; + } + const file = path.join(ROOT, path.normalize(decodeURIComponent(url.pathname)).replace(/^(\.\.[/\\])+/, '')); + if (!file.startsWith(ROOT) || !existsSync(file) || statSync(file).isDirectory()) { + response.writeHead(404, { 'content-type': 'text/plain' }); + response.end('Not found'); + return; + } + response.writeHead(200, { 'content-type': TYPES[path.extname(file)] ?? 'application/octet-stream', 'cache-control': 'no-store' }); + createReadStream(file).pipe(response); + } + + /** + * `/ws` accepts the handshake and holds the socket open, as Playwright's + * server does, so an open WebSocket is in the page during network-idle tests. + */ + function upgrade(request, socket) { + const key = request.headers['sec-websocket-key']; + if (new URL(request.url, 'http://localhost').pathname !== '/ws' || typeof key !== 'string') { + socket.destroy(); + return; + } + const accept = createHash('sha1').update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest('base64'); + socket.on('error', () => socket.destroy()); + socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`); + } + + return { handle, upgrade }; +} diff --git a/apps/testbed/app/server.mjs b/apps/testbed/app/server.mjs index ef34d5c70d..6edc97cad1 100644 --- a/apps/testbed/app/server.mjs +++ b/apps/testbed/app/server.mjs @@ -1,14 +1,17 @@ /** * Playground app for dogfooding the e2e runner. No dependencies. The pages * live under `pages/` by group; this file serves them, the API, and the - * cookie session. + * cookie session. Any other path goes to the routes of the tests ported from + * Playwright (`playwright/`). */ import { createServer } from 'node:http'; import { layout } from './layout.mjs'; import { pages } from './pages/index.mjs'; +import { playwrightRoutes } from './playwright/routes.mjs'; const PORT = Number(process.env.PORT ?? 4271); +const playwright = playwrightRoutes(PORT); function parseCookies(request) { const header = request.headers.cookie ?? ''; @@ -76,12 +79,14 @@ const server = createServer(async (request, response) => { } if (!(url.pathname in pages)) { - send(404, { 'content-type': 'text/plain' }, 'not found'); + await playwright.handle(request, response); return; } html(render(url.pathname)); }); +server.on('upgrade', playwright.upgrade); + server.listen(PORT, '127.0.0.1', () => { console.log(`playground listening on http://127.0.0.1:${PORT}`); }); diff --git a/apps/testbed/e2e.mixed.config.ts b/apps/testbed/e2e.mixed.config.ts index 28b27ec81f..7301453f44 100644 --- a/apps/testbed/e2e.mixed.config.ts +++ b/apps/testbed/e2e.mixed.config.ts @@ -4,7 +4,9 @@ import agentConfig from './e2e.agent.config.ts'; /** * The agent config plus the deterministic suite, for watching the list * reporter interleave agent steps with plain tests. Needs the same - * `AI_GATEWAY_API_KEY` as `test:agent`; never part of CI. + * `AI_GATEWAY_API_KEY` as `test:agent`; never part of CI. Pass + * `--exclude-tag playwright`: the tests ported from Playwright address the + * playground on its own port, 4271. */ export default { ...agentConfig, diff --git a/apps/testbed/package.json b/apps/testbed/package.json index ddf182e9fb..1244f21199 100644 --- a/apps/testbed/package.json +++ b/apps/testbed/package.json @@ -8,7 +8,7 @@ "typecheck": "tsc --noEmit", "test": "tsc --noEmit && node node_modules/e2e/dist/cli/bin.js run", "test:headed": "node node_modules/e2e/dist/cli/bin.js run --headed", - "test:lightpanda": "node node_modules/e2e/dist/cli/bin.js run --config e2e.lightpanda.config.ts", + "test:lightpanda": "node node_modules/e2e/dist/cli/bin.js run --config e2e.lightpanda.config.ts --exclude-tag playwright", "test:lightpanda:agent": "node node_modules/e2e/dist/cli/bin.js run --config e2e.lightpanda-agent.config.ts", "app": "node app/server.mjs", "test:agent": "node node_modules/e2e/dist/cli/bin.js run --config e2e.agent.config.ts", @@ -27,7 +27,9 @@ "devDependencies": { "@ai-sdk/devtools": "1.0.65", "@types/node": "26.6.6", + "@types/pngjs": "6.0.5", "ai": "7.0.162", + "pngjs": "7.0.0", "typescript": "7.0.2", "zod": "4.6.7" } diff --git a/apps/testbed/tests/browser.e2e.ts b/apps/testbed/tests/browser.e2e.ts index 62241a104e..2384655bf4 100644 --- a/apps/testbed/tests/browser.e2e.ts +++ b/apps/testbed/tests/browser.e2e.ts @@ -21,12 +21,6 @@ test.describe('browser fixture', { requires: ['browser'], tags: ['browser'] }, ( await expect(browser).toHaveURL(/about$/); }); - test('waitForURL waits out a delayed navigation', async ({ screen, browser }) => { - await screen.getByRole('button', 'Go to about, soon').tap(); - await browser.waitForURL('/about'); - await expect(screen.getByRole('heading', 'About')).toBeVisible(); - }); - test('reload runs the page again', async ({ screen, browser }) => { await expect(screen.getByLabel('Loads')).toHaveText('loads: 1'); await browser.reload(); diff --git a/apps/testbed/tests/check.e2e.ts b/apps/testbed/tests/check.e2e.ts new file mode 100644 index 0000000000..38dca1edd1 --- /dev/null +++ b/apps/testbed/tests/check.e2e.ts @@ -0,0 +1,117 @@ +/** + * Adapted from microsoft/playwright tests/page/page-check.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `page.check(selector)` is a locator check. + */ + +/* + * Not ported: + * - should check the label with position: `check` takes no `position`. + * - trial run should not check: no `trial` option. + * - trial run should not uncheck: no `trial` option. + * - should check the box using setChecked: no `setChecked`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('page check', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should check the box', async ({ browser }) => { + await browser.goto(content("")); + await browser.locator('input').check(); + expect(await browser.evaluate('() => window.checkbox.checked')).toBe(true); + }); + + test('should not check the checked box', async ({ browser }) => { + await browser.goto(content("")); + await browser.locator('input').check(); + expect(await browser.evaluate('() => window.checkbox.checked')).toBe(true); + }); + + test('should uncheck the box', async ({ browser }) => { + await browser.goto(content("")); + await browser.locator('input').uncheck(); + expect(await browser.evaluate('() => window.checkbox.checked')).toBe(false); + }); + + test('should not uncheck the unchecked box', async ({ browser }) => { + await browser.goto(content("")); + await browser.locator('input').uncheck(); + expect(await browser.evaluate('() => window.checkbox.checked')).toBe(false); + }); + + test('should check radio', async ({ browser }) => { + await browser.goto(content(` + one + two + three`)); + await browser.locator('#two').check(); + expect(await browser.evaluate('() => window.two.checked')).toBe(true); + }); + + test('should check radio by aria role', async ({ browser }) => { + await browser.goto(content(` + `)); + await browser.locator('div').check(); + expect(await browser.evaluate("() => window.checkbox.getAttribute('aria-checked')")).toBe('true'); + }); + + test('should uncheck radio by aria role', { fail: '`uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio' }, async ({ browser }) => { + await browser.goto(content(` + `)); + await browser.locator('div').uncheck(); + expect(await browser.evaluate("() => window.checkbox.getAttribute('aria-checked')")).toBe('false'); + }); + + test('should check the box by aria role', async ({ browser }) => { + for (const role of ['checkbox', 'menuitemcheckbox', 'option', 'radio', 'switch', 'menuitemradio', 'treeitem']) { + await browser.goto(content(`
CHECKBOX
+ `)); + await browser.locator('div').check(); + expect(await browser.evaluate("() => window.checkbox.getAttribute('aria-checked')")).toBe('true'); + } + }); + + test('should uncheck the box by aria role', { fail: '`uncheck` refuses a `role=radio`, where Playwright clicks it and refuses only a native radio' }, async ({ browser }) => { + for (const role of ['checkbox', 'menuitemcheckbox', 'option', 'radio', 'switch', 'menuitemradio', 'treeitem']) { + await browser.goto(content(`
CHECKBOX
+ `)); + await browser.locator('div').uncheck(); + expect(await browser.evaluate("() => window.checkbox.getAttribute('aria-checked')")).toBe('false'); + } + }); + + test('should throw when not a checkbox', async ({ browser }) => { + await browser.goto(content('
Check me
')); + const error = await browser.locator('div').check().catch((caught: Error) => caught); + expect((error as Error).message).toContain('Not a checkbox or radio button'); + }); + + test('should throw when not a checkbox 2', async ({ browser }) => { + await browser.goto(content('
Check me
')); + const error = await browser.locator('div').check().catch((caught: Error) => caught); + expect((error as Error).message).toContain('Not a checkbox or radio button'); + }); + + test('should check the box inside a button', async ({ browser }) => { + await browser.goto(content("
")); + await browser.locator('input').check(); + expect(await browser.evaluate("() => document.querySelector('input').checked")).toBe(true); + expect(await browser.locator('input').isChecked()).toBe(true); + }); + + test('should throw when trying to uncheck radio button', async ({ browser }) => { + await browser.goto(content("")); + const error = await browser.locator('#radio').uncheck().catch((caught: Error) => caught); + expect((error as Error).message).toContain('uncheck cannot clear a radio button'); + }); +}); diff --git a/apps/testbed/tests/click-scroll.e2e.ts b/apps/testbed/tests/click-scroll.e2e.ts new file mode 100644 index 0000000000..3d3fcfbb23 --- /dev/null +++ b/apps/testbed/tests/click-scroll.e2e.ts @@ -0,0 +1,103 @@ +/** + * Adapted from microsoft/playwright tests/page/page-click-scroll.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `page.click(selector)` is a locator + * tap, a `text=` selector a substring `getByText`. + * + * Not ported: + * - should not crash when force-clicking hidden input: e2e tap has no force option. + * - should not scroll the page when scroll is "none": e2e tap has no scroll option. + * - should click in-viewport element when scroll is "none": same. + * - should not scroll nested container when scroll is "none": same. + * - should not scroll on hover when scroll is "none": same, and a `>>` chain. + * - should scroll into view display:contents with position: Playwright skips it on Chromium. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, CROSS } from './helpers.ts'; + +test.describe('page click scroll', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should not hit scroll bar', async ({ screen, browser }) => { + await browser.goto(content(` + +
+ + + + + + + +
+ `)); + await screen.getByText('Story', { exact: false }).tap({ timeout: 2000 }); + }); + + test('should scroll into view display:contents', async ({ screen, browser }) => { + await browser.goto(content(` +
filler
+
+ Example text, and button here: + +
+ `)); + await screen.getByText('click me', { exact: false }).tap({ timeout: 5000 }); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should scroll into view display:contents with a child', async ({ screen, browser }) => { + await browser.goto(content(` +
filler
+ Example text, and button here: + + `)); + await screen.getByText('click me', { exact: false }).tap({ timeout: 5000 }); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should scroll into view span element', async ({ browser }) => { + await browser.goto(content(` +
+ foo + `)); + await browser.locator('#small').scrollIntoView(); + expect(await browser.evaluate('() => window.scrollY')).toBeGreaterThan(9000); + }); + + test('should scroll into view element in iframe', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(` +
+ + `)); + await browser.frameLocator('iframe').getByRole('button').tap({ timeout: 5000 }); + }); + + test('should scroll instantly on retry when scroll-behavior is smooth', async ({ browser }) => { + await browser.goto(content(` + + +
+ +
+ + `)); + await browser.locator('button').tap(); + expect(await browser.evaluate('window.clicked')).toBe(true); + const scrolls = await browser.evaluate("() => window['scrolls']"); + expect(scrolls.length).toBeLessThanOrEqual(2); + }); +}); diff --git a/apps/testbed/tests/click.e2e.ts b/apps/testbed/tests/click.e2e.ts new file mode 100644 index 0000000000..d0bef1dcb8 --- /dev/null +++ b/apps/testbed/tests/click.e2e.ts @@ -0,0 +1,598 @@ +/** + * Adapted from microsoft/playwright tests/page/page-click.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `page.click(selector)` is a locator tap. + * + * Not ported: + * - should click button inside frameset: needs element handles and Frame objects. + * - should issue clicks in parallel in page and popup: needs `waitForEvent('popup')`. + * - should select the text by triple clicking: no `clickCount`. + * - should waitFor visible when already visible: could be ported with the current API; not done yet. + * - should not wait with force: e2e tap has no force option. + * - should click the button with fixed position inside an iframe: Playwright skips it on Chromium (`it.fixme(browserName === 'chromium')`). + * - should click the button with px border with offset: could be ported with the current API; not done yet. + * - should click the button with em border with offset: could be ported with the current API; not done yet. + * - should click a very large button with offset: a `position` tap scrolls the node into view, not the offset point. + * - should click a button in scrolling container with offset: same. + * - should wait for becoming hit target with trial run: no `trial` option. + * - trial run should work with short timeout: same. + * - trial run should not click: same. + * - trial run should not double click: same. + * - should fail when obscured and not waiting for hit target: e2e tap has no force option. + * - should wait for LABEL to be clickable when it has pointer-events:none: could be ported with the current API; not done yet. + * - should report nice error when element is detached and force-clicked: needs element handles, and e2e tap has no force option. + * - should fail when element detaches after animation: needs element handles. + * - should retry when element detaches after animation: could be ported with the current API; not done yet. + * - should retry when element is animating from outside the viewport: could be ported with the current API; not done yet. + * - should fail when element is animating from outside the viewport with force: e2e tap has no force option. + * - should dispatch microtasks in order: could be ported with the current API; not done yet. + * - should not throw protocol error when navigating during the click: needs Playwright's `__testHookBeforeStable`. + * - should retry when navigating during the click: same. + * - should not hang when frame is detached: same, and needs Frame objects. + * - should click in an iframe with border 2: could be ported with the current API; not done yet. + * - should not retain removed iframe after clicking inside it: needs `page.requestGC`. + * - should click a button that is overlaid by a permission popup: could be ported with the current API; not done yet. + * - should click in a transformed iframe with force: e2e tap has no force option. + * - ensure events are dispatched in the individual tasks: needs `page.on('console')`. + * - should set PointerEvent.pressure on pointerdown: could be ported with the current API; not done yet. + * - should set PointerEvent.pressure on pointermove: could be ported with the current API; not done yet. + * - should click with tweened mouse movement: needs click `steps`. + * - should abort via signal: needs `AbortSignal`. + * - should throw an Error when aborted in-flight with a string reason: same. + * - should abort via already-aborted signal: same. + * - should throw an Error when aborted via an already-aborted signal with a string reason: same. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, CROSS } from './helpers.ts'; + +/** Two animation frames and a task, Playwright's `rafraf`, so a pending tap has had its chance. */ +const giveItAChanceToClick = '() => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(resolve, 0))))'; + +test.describe('page click', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should click the button', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click svg', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + await browser.locator('circle').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(42); + }); + + test('should click the button if window.Node is removed', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate('() => { delete window.Node; }'); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click on a span with an inline element inside', async ({ browser }) => { + await browser.goto(content(` + + + `)); + await browser.locator('span').tap(); + expect(await browser.evaluate('CLICKED')).toBe(42); + }); + + for (const [name, style] of [ + ['aligned', ''], + ['half-aligned', 'margin-left: 20.5px; margin-top: 11.5px;'], + ['unaligned v1', 'margin-left: 20.23px; margin-top: 11.65px;'], + ['unaligned v2', 'margin-left: 20.68px; margin-top: 11.13px;'], + ['unaligned v3', 'margin-left: 20.68px; margin-top: 11.52px;'], + ['unaligned v4', 'margin-left: 20.15px; margin-top: 11.24px;'], + ] as const) { + test(`should click the ${name} 1x1 div`, async ({ browser }) => { + await browser.goto(content(`
`)); + await browser.locator('div').tap(); + expect(await browser.evaluate('window.__clicked')).toBe(true); + }); + } + + test('should click the button after navigation', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.locator('button').tap(); + await browser.goto('/input/button.html'); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click the button after a cross origin navigation', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.locator('button').tap(); + await browser.goto(`${CROSS}/input/button.html`); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click when one of inline box children is outside of viewport', async ({ browser }) => { + await browser.goto(content(` + + woofdoggo + `)); + await browser.locator('span').tap(); + expect(await browser.evaluate('CLICKED')).toBe(42); + }); + + test('should click offscreen buttons', async ({ browser }) => { + await browser.goto('/offscreenbuttons.html'); + await browser.evaluate('() => { window.messages = []; console.log = (text) => window.messages.push(text); }'); + for (let index = 0; index < 11; ++index) { + await browser.evaluate('() => window.scrollTo(0, 0)'); + await browser.locator(`#btn${index}`).tap(); + } + expect(await browser.evaluate('messages')).toEqual(Array.from({ length: 11 }, (_, index) => `button #${index} clicked`)); + }); + + test('should waitFor display:none to be gone', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { document.querySelector('button').style.display = 'none'; }"); + let done = false; + const clicked = browser.locator('button').tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(await browser.evaluate('result')).toBe('Was not clicked'); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('button').style.display = 'block'; }"); + await clicked; + expect(done).toBe(true); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should waitFor visibility:hidden to be gone', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { document.querySelector('button').style.visibility = 'hidden'; }"); + let done = false; + const clicked = browser.locator('button').tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(await browser.evaluate('result')).toBe('Was not clicked'); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('button').style.visibility = 'visible'; }"); + await clicked; + expect(done).toBe(true); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should waitFor visible when parent is hidden', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { document.querySelector('button').parentElement.style.display = 'none'; }"); + let done = false; + const clicked = browser.locator('button').tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('button').parentElement.style.display = 'block'; }"); + await clicked; + expect(done).toBe(true); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click wrapped links', async ({ browser }) => { + await browser.goto('/wrappedlink.html'); + await browser.locator('a').tap(); + expect(await browser.evaluate('__clicked')).toBe(true); + }); + + test('should click on checkbox input and toggle', async ({ browser }) => { + await browser.goto('/input/checkbox.html'); + expect(await browser.evaluate('() => window.result.check')).toBe(null); + await browser.locator('input#agree').tap(); + expect(await browser.evaluate('() => window.result.check')).toBe(true); + expect(await browser.evaluate('() => window.result.events')).toEqual(['mouseover', 'mouseenter', 'mousemove', 'mousedown', 'mouseup', 'click', 'input', 'change']); + await browser.locator('input#agree').tap(); + expect(await browser.evaluate('() => window.result.check')).toBe(false); + }); + + test('should click on checkbox label and toggle', async ({ browser }) => { + await browser.goto('/input/checkbox.html'); + expect(await browser.evaluate('() => window.result.check')).toBe(null); + await browser.locator('label[for="agree"]').tap(); + expect(await browser.evaluate('() => window.result.check')).toBe(true); + expect(await browser.evaluate('() => window.result.events')).toEqual(['click', 'input', 'change']); + await browser.locator('label[for="agree"]').tap(); + expect(await browser.evaluate('() => window.result.check')).toBe(false); + }); + + test('should scroll and click the button', async ({ browser }) => { + await browser.goto('/input/scrollable.html'); + await browser.locator('#button-5').tap(); + expect(await browser.evaluate("() => document.querySelector('#button-5').textContent")).toBe('clicked'); + await browser.locator('#button-80').tap(); + expect(await browser.evaluate("() => document.querySelector('#button-80').textContent")).toBe('clicked'); + }); + + test('should scroll and click the button with smooth scroll behavior', async ({ browser }) => { + await browser.goto('/input/scrollable.html'); + await browser.evaluate("() => { const style = document.createElement('style'); style.textContent = 'html { scroll-behavior: smooth; }'; document.head.append(style); }"); + for (let index = 0; index < 5; index++) { + await browser.locator('#button-80').tap(); + expect(await browser.evaluate("() => document.querySelector('#button-80').textContent")).toBe('clicked'); + await browser.locator('#button-20').tap(); + expect(await browser.evaluate("() => document.querySelector('#button-20').textContent")).toBe('clicked'); + } + }); + + test('should double click the button', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { window.double = false; document.querySelector('button').addEventListener('dblclick', () => { window.double = true; }); }"); + await browser.locator('button').doubleTap(); + expect(await browser.evaluate('double')).toBe(true); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click a partially obscured button', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { const button = document.querySelector('button'); button.textContent = 'Some really long text that will go offscreen'; button.style.position = 'absolute'; button.style.left = '368px'; }"); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click a rotated button', async ({ browser }) => { + await browser.goto('/input/rotatedButton.html'); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should fire contextmenu event on right click', async ({ browser }) => { + await browser.goto('/input/scrollable.html'); + await browser.locator('#button-8').secondaryTap(); + expect(await browser.evaluate("() => document.querySelector('#button-8').textContent")).toBe('context menu'); + }); + + test('should click links which cause navigation', async ({ browser }) => { + await browser.goto(content('empty.html')); + await browser.locator('a').tap(); + await browser.waitForURL('/empty.html'); + }); + + test('should click the button inside an iframe', async ({ browser }) => { + await browser.goto(content('
spacer
')); + const frame = browser.frameLocator('iframe'); + await frame.locator('button').tap(); + expect(await browser.evaluate("() => document.querySelector('iframe').contentWindow.result")).toBe('Clicked'); + }); + + test('should click the button behind sticky header', async ({ browser }) => { + await browser.setViewport({ width: 500, height: 240 }); + await browser.goto(content(` + +
+
    +
  1. hi1
  2. hi2
  3. hi3
  4. hi4
  5. hi5
  6. hi6
  7. hi7
  8. hi8
  9. +
  10. hi9
  11. +
  12. hi10
  13. hi11
  14. hi12
  15. hi13
  16. hi14
  17. +
+ `)); + await browser.evaluate("() => document.querySelector('#li14').scrollIntoView()"); + await browser.locator('#target').tap(); + expect(await browser.evaluate('() => window.__clicked')).toBe(true); + }); + + test('should click the button behind position:absolute header', async ({ browser }) => { + await browser.setViewport({ width: 500, height: 240 }); + await browser.goto(content(` + +
    +
  1. hi1
  2. hi2
  3. hi3
  4. hi4
  5. hi5
  6. hi6
  7. hi7
  8. hi8
  9. +
  10. hi9
  11. +
  12. hi10
  13. hi11
  14. hi12
  15. hi13
  16. hi14
  17. +
+
Overlay
+ `)); + await browser.evaluate("() => { const target = document.querySelector('#target'); document.querySelector('ol').scrollTo({ top: target.offsetTop, behavior: 'instant' }); }"); + await browser.locator('#target').tap(); + expect(await browser.evaluate('() => window.__clicked')).toBe(true); + }); + + test('should wait for stable position', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate(`() => { + const button = document.querySelector('button'); + button.style.transition = 'margin 500ms linear 0s'; + button.style.marginLeft = '200px'; + button.style.borderWidth = '0'; + button.style.width = '200px'; + button.style.height = '20px'; + button.style.display = 'block'; + document.body.style.margin = '0'; + }`); + await browser.evaluate(giveItAChanceToClick); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + expect(await browser.evaluate('pageX')).toBe(300); + expect(await browser.evaluate('pageY')).toBe(10); + }); + + test('should wait for becoming hit target', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate(`() => { + const button = document.querySelector('button'); + button.style.borderWidth = '0'; + button.style.width = '200px'; + button.style.height = '20px'; + document.body.style.margin = '0'; + document.body.style.position = 'relative'; + const flyOver = document.createElement('div'); + flyOver.className = 'flyover'; + flyOver.style.position = 'absolute'; + flyOver.style.width = '400px'; + flyOver.style.height = '20px'; + flyOver.style.left = '-200px'; + flyOver.style.top = '0'; + flyOver.style.background = 'red'; + document.body.appendChild(flyOver); + }`); + let clicked = false; + const tap = browser.locator('button').tap({ timeout: 10_000 }).then(() => (clicked = true)); + expect(clicked).toBe(false); + await browser.evaluate("() => { document.querySelector('.flyover').style.left = '0'; }"); + await browser.evaluate(giveItAChanceToClick); + expect(clicked).toBe(false); + await browser.evaluate("() => { document.querySelector('.flyover').style.left = '200px'; }"); + await tap; + expect(clicked).toBe(true); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + for (const [name, html, enable] of [ + ['button', '', "document.querySelector('button').removeAttribute('disabled')"], + ['input', '', "document.querySelector('input').removeAttribute('disabled')"], + ] as const) { + test(`should wait for ${name} to be enabled`, async ({ browser, screen }) => { + await browser.goto(content(html)); + let done = false; + const tap = (name === 'button' ? screen.getByText('Click target') : browser.locator(name)).tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(await browser.evaluate('() => window.__CLICKED')).toBeUndefined(); + expect(done).toBe(false); + await browser.evaluate(`() => { ${enable}; }`); + await tap; + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + } + + test('should wait for select to be enabled', async ({ browser }) => { + await browser.goto(content(` + + + `)); + let done = false; + const tap = browser.locator('select').tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(await browser.evaluate('() => window.__CLICKED')).toBeUndefined(); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('select').removeAttribute('disabled'); }"); + await tap; + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should click disabled div', async ({ browser, screen }) => { + await browser.goto(content('
Click target
')); + await screen.getByText('Click target').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should wait for BUTTON to be clickable when it has pointer-events:none', async ({ browser, screen }) => { + await browser.goto(content('')); + let done = false; + const tap = screen.getByText('Click target').tap({ timeout: 10_000 }).then(() => (done = true)); + await browser.evaluate(giveItAChanceToClick); + expect(await browser.evaluate('() => window.__CLICKED')).toBeUndefined(); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('button').style.removeProperty('pointer-events'); }"); + await tap; + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should update modifiers correctly', async ({ browser }) => { + await browser.goto('/input/button.html'); + const button = browser.locator('button'); + await button.tap({ modifiers: ['Shift'] }); + expect(await browser.evaluate('shiftKey')).toBe(true); + await button.tap(); + expect(await browser.evaluate('shiftKey')).toBe(false); + await browser.keyboard.down('Shift'); + await button.tap(); + expect(await browser.evaluate('shiftKey')).toBe(true); + await browser.keyboard.up('Shift'); + await button.tap(); + expect(await browser.evaluate('shiftKey')).toBe(false); + }); + + test('should click an offscreen element when scroll-behavior is smooth', async ({ browser }) => { + await browser.goto(content(` +
+ +
+ `)); + await browser.locator('button').tap(); + expect(await browser.evaluate('window.clicked')).toBe(true); + }); + + test('should click the button when window.innerWidth is corrupted', async ({ browser }) => { + await browser.goto('/input/button.html'); + await browser.evaluate("() => { Object.defineProperty(window, 'innerWidth', { value: 0 }); }"); + await browser.locator('button').tap(); + expect(await browser.evaluate('result')).toBe('Clicked'); + }); + + test('should click zero-sized input by label', async ({ browser, screen }) => { + await browser.goto(content(` + + `)); + await screen.getByText('Click me').tap(); + expect(await browser.evaluate('window.__clicked')).toBe(true); + }); + + test('should climb dom for inner label with pointer-events:none', async ({ browser, screen }) => { + await browser.goto(content('')); + await screen.getByText('Click target').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should climb up to [role=button]', async ({ browser, screen }) => { + await browser.goto(content('
Click target
')); + await screen.getByText('Click target').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should climb up to a anchor', async ({ browser }) => { + await browser.goto(content('
Inner
')); + await browser.locator('#inner').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should climb up to a [role=link]', async ({ browser }) => { + await browser.goto(content('
Inner
')); + await browser.locator('#inner').tap(); + expect(await browser.evaluate('__CLICKED')).toBe(true); + }); + + test('should click in an iframe with border', async ({ browser }) => { + await browser.goto(content(` + + + `)); + await browser.frameLocator('iframe').locator('div').tap(); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should click in a transformed iframe', async ({ browser }) => { + await browser.goto(content(` + + + `)); + await browser.frameLocator('iframe').locator('div').tap(); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should click in a nested transformed iframe', async ({ browser }) => { + await browser.goto(content(` + + + `)); + await browser.frameLocator('iframe').frameLocator('iframe').locator('div').tap(); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); + + test('should click if opened select covers the button', async ({ browser }) => { + await browser.goto(content(` +
+ +
+
+ `)); + await browser.locator('select').tap(); + await browser.locator('button').tap(); + expect(await browser.evaluate('window.__CLICKED')).toBe(42); + }); + + test('should fire contextmenu event on right click in correct order', async ({ browser, screen }) => { + await browser.goto(content('')); + await browser.evaluate("() => { window.entries = []; const log = (event) => window.entries.push(event.type); for (const type of ['mousedown', 'mouseup', 'contextmenu']) document.addEventListener(type, log); }"); + await screen.getByRole('button', 'Click me').secondaryTap(); + await expect.poll(() => browser.evaluate('entries')).toEqual(['mousedown', 'contextmenu', 'mouseup']); + }); + + test('should click after a right click', async ({ browser, screen }) => { + await browser.goto(content(` + + + `)); + await screen.getByRole('button').secondaryTap(); + await screen.getByRole('button').tap(); + await expect(screen.getByRole('button')).toHaveText('Clicked!'); + }); + + test('should click into shadow root with slotted div', async ({ browser, screen }) => { + await browser.goto(content(` + + +
Foo
+
+ `)); + await screen.getByRole('button', 'Foo').tap(); + expect(await browser.evaluate('window.__clicked')).toBe(true); + }); + + test('should click shadow root button', async ({ browser }) => { + await browser.goto(content(` + + +
Foo
+
+ `)); + await browser.locator('my-button').tap(); + expect(await browser.evaluate('window.__clicked')).toBe(true); + }); +}); diff --git a/apps/testbed/tests/controls.e2e.ts b/apps/testbed/tests/controls.e2e.ts index 0ee6863b47..d76fee0180 100644 --- a/apps/testbed/tests/controls.e2e.ts +++ b/apps/testbed/tests/controls.e2e.ts @@ -1,6 +1,6 @@ import { test } from '@e2e-dev/web'; import { expect } from 'e2e'; -import { boxOf, failure } from './helpers.ts'; +import { failure } from './helpers.ts'; test.describe('controls', { requires: ['browser'], tags: ['controls'] }, () => { test.beforeEach(async ({ app }) => { @@ -213,15 +213,6 @@ test.describe('controls', { requires: ['browser'], tags: ['controls'] }, () => { expect(error).toHaveProperty('message', expect.stringContaining('opened no file chooser')); }); - test('scrollIntoView brings a node far below into the viewport', async ({ screen }) => { - const footnote = screen.getByText('Footnote', { exact: true }); - await expect(screen.getByLabel('Footnote state')).toHaveText('out of view'); - - await footnote.scrollIntoView(); - await expect(screen.getByLabel('Footnote state')).toHaveText('in view'); - expect((await boxOf(footnote)).y).toBeGreaterThanOrEqual(0); - }); - test('a missing locator fails as LOCATOR_NOT_FOUND after its timeout', async ({ screen }) => { expect(await failure(() => screen.getByRole('button', 'Nope').tap({ timeout: 500 }))).toHaveProperty( 'code', diff --git a/apps/testbed/tests/dialog.e2e.ts b/apps/testbed/tests/dialog.e2e.ts new file mode 100644 index 0000000000..4185ca2333 --- /dev/null +++ b/apps/testbed/tests/dialog.e2e.ts @@ -0,0 +1,124 @@ +/** + * Adapted from microsoft/playwright tests/page/page-dialog.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `page.on('dialog')` is `browser.onDialog`. A dialog no + * handler answers is dismissed as in Playwright, and e2e also fails the next step for it. + */ + +/* + * Not ported: + * - should fire dialogclosed when dialog is accepted: the dialogclosed event. + * - should fire dialogclosed when dialog is dismissed: the dialogclosed event. + * - should fire dialogclosed for auto-dismissed dialogs: the dialogclosed event. + * - should be able to close context with open alert: e2e answers every dialog, so none stays open. + * The `defaultValue()` assertions of the kept tests are dropped: e2e dialogs have no default value. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +/** What `act` threw, or undefined when it did not throw. */ +async function failure(act: () => unknown): Promise { + try { + await act(); + return undefined; + } catch (error) { + return error; + } +} + +test.describe('page dialog', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should fire', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.onDialog(async (dialog) => { + expect(dialog.type).toBe('alert'); + expect(dialog.message).toBe('yo'); + await dialog.accept(); + }); + await browser.evaluate("() => alert('yo')"); + }); + + test('should allow accepting prompts', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.onDialog(async (dialog) => { + expect(dialog.type).toBe('prompt'); + expect(dialog.message).toBe('question?'); + await dialog.accept('answer!'); + }); + const result = await browser.evaluate("() => prompt('question?', 'yes.')"); + expect(result).toBe('answer!'); + }); + + test('should dismiss the prompt', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.onDialog((dialog) => dialog.dismiss()); + const result = await browser.evaluate("() => prompt('question?')"); + expect(result).toBe(null); + }); + + test('should accept the confirm prompt', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.onDialog(async (dialog) => { + await dialog.accept(); + }); + const result = await browser.evaluate("() => confirm('boolean?')"); + expect(result).toBe(true); + }); + + test('should dismiss the confirm prompt', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.onDialog(async (dialog) => { + await dialog.dismiss(); + }); + const result = await browser.evaluate("() => confirm('boolean?')"); + expect(result).toBe(false); + }); + + test('should handle multiple alerts', async ({ browser }) => { + await browser.onDialog(async (dialog) => { + await dialog.accept().catch(() => {}); + }); + await browser.goto(content(` +

Hello World

+ + `)); + expect(await browser.locator('p').textContent()).toBe('Hello World'); + }); + + test('should handle multiple confirms', async ({ browser }) => { + await browser.onDialog(async (dialog) => { + await dialog.accept().catch(() => {}); + }); + await browser.goto(content(` +

Hello World

+ + `)); + expect(await browser.locator('p').textContent()).toBe('Hello World'); + }); + + test('should auto-dismiss the prompt without listeners', async ({ browser }) => { + await browser.goto('/empty.html'); + const result = await browser.evaluate("() => prompt('question?')"); + expect(result).toBe(null); + expect(String(await failure(() => browser.title()))).toContain('unhandled prompt dialog: question?'); + }); + + test('should auto-dismiss the alert without listeners', async ({ browser }) => { + await browser.goto(content(`
Click me
`)); + const error = await failure(async () => { + await browser.locator('div').tap(); + await browser.title(); + }); + expect(String(error)).toContain('unhandled alert dialog: 123'); + expect(await browser.evaluate('window._clicked')).toBe(true); + }); +}); diff --git a/apps/testbed/tests/dialogs-frames.e2e.ts b/apps/testbed/tests/dialogs-frames.e2e.ts index 1aeb98241c..c70d794ba0 100644 --- a/apps/testbed/tests/dialogs-frames.e2e.ts +++ b/apps/testbed/tests/dialogs-frames.e2e.ts @@ -26,19 +26,6 @@ test.describe('dialogs', { requires: ['browser'] }, () => { expect(await failure(() => browser.title())).toHaveProperty('code', 'ENGINE_FAILURE'); expect(await browser.title()).toBe('Dialogs'); }); - - test('custom dialog handlers read the message', async ({ app, screen, browser }) => { - await app.open('/dialogs'); - let message = ''; - const dispose = await browser.onDialog(async (dialog) => { - message = dialog.message; - await dialog.accept(); - }); - await screen.getByRole('button', 'Delete everything').tap(); - await expect(screen.getByRole('status', 'Decision')).toHaveText('deleted'); - expect(message).toBe('Really delete everything?'); - await dispose(); - }); }); test.describe('frames', { requires: ['browser'] }, () => { diff --git a/apps/testbed/tests/download.e2e.ts b/apps/testbed/tests/download.e2e.ts new file mode 100644 index 0000000000..6ac7c4fe17 --- /dev/null +++ b/apps/testbed/tests/download.e2e.ts @@ -0,0 +1,217 @@ +/** + * Adapted from microsoft/playwright tests/library/download.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `page.waitForEvent('download')` is `browser.waitForDownload(trigger)`, + * which saves the file, and `download.path()` is the saved file's `absolutePath`. e2e has no + * `download.url()`, so its assertions are dropped. + */ + +/* + * Not ported: + * - should report downloads with acceptDownloads: false: e2e always accepts downloads. + * - should report proper download url when download is from download attribute: needs `download.url()`. + * - should save to user-specified path without updating original path: needs `download.saveAs`. + * - should save to two different paths with multiple saveAs calls: needs `download.saveAs`. + * - should save to overwritten filepath: needs `download.saveAs`. + * - should create subdirectories when saving to non-existent user-specified path: needs `download.saveAs`. + * - should error when saving with downloads disabled: needs `acceptDownloads: false` and `download.saveAs`. + * - should error when saving after deletion: needs `download.delete` and `download.saveAs`. + * - should delete file: needs `download.delete`. + * - should expose stream: needs `download.createReadStream`. + * - should delete downloads on context destruction: needs `context.close` from the test. + * - should delete downloads on browser gone: needs `browserType.launch` from the test. + * - should save downloads to artifactsDir: needs `browserType.launch({ artifactsDir })`. + * - should close the context without awaiting the failed download: needs `context.close` and an HTTPS server. + * - should close the context without awaiting the download: needs `context.close` and `download.failure`. + * - should throw if browser dies: needs `browser.close` from the test. + * - should be able to cancel pending downloads: needs `download.cancel` and `download.failure`. + * - should not fail explicitly to cancel a download even if that is already finished: needs `download.cancel`. + * - should save to user-specified path: needs `download.saveAs`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import fs from 'node:fs'; +import path from 'node:path'; +import { asset, content, PREFIX } from './helpers.ts'; + +/** `/respond` answering with `headers` and `body`. */ +function respond(headers: Record, body = 'Hello world'): string { + return `/respond?headers=${encodeURIComponent(JSON.stringify(headers))}&body=${encodeURIComponent(body)}`; +} + +/** Checks a saved download is the file at `filePath` byte for byte, PDF magic first, Playwright's `assertDownloadToPDF`. */ +function assertDownloadToPDF(download: { absolutePath: string; suggestedFilename: string }, filePath: string): void { + expect(download.suggestedFilename).toBe(path.basename(filePath)); + const data = fs.readFileSync(download.absolutePath); + const expectedPrefix = '%PDF'; + for (let i = 0; i < expectedPrefix.length; i++) expect(data[i]).toBe(expectedPrefix.charCodeAt(i)); + expect(data.equals(fs.readFileSync(filePath))).toBe(true); +} + +test.describe('download event', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should report download when navigation turns into download @smoke', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto('/empty.html'); + let responseOrError: unknown; + const download = await browser.waitForDownload(async () => { + responseOrError = await browser.goto(`${PREFIX}/download`).catch((caught: Error) => caught); + }); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + expect(responseOrError instanceof Error).toBeTruthy(); + expect((responseOrError as Error).message).toContain('Download is starting'); + expect(await browser.url()).toBe(`${PREFIX}/empty.html`); + }); + + test('should work with Cross-Origin-Opener-Policy', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto('/empty.html'); + let responseOrError: unknown; + const url = respond({ 'content-type': 'application/octet-stream', 'content-disposition': 'attachment', 'cross-origin-opener-policy': 'same-origin' }); + const download = await browser.waitForDownload(async () => { + responseOrError = await browser.goto(url).catch((caught: Error) => caught); + }); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + expect(responseOrError instanceof Error).toBeTruthy(); + expect((responseOrError as Error).message).toContain('Download is starting'); + expect(await browser.url()).toBe(`${PREFIX}/empty.html`); + }); + + test('should report downloads with acceptDownloads: true', async ({ browser }) => { + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test('should report downloads for download attribute', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(download.suggestedFilename).toBe('foo.zip'); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + }); + + test('should report non-navigation downloads', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(download.suggestedFilename).toBe('file.txt'); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test(`should report download path within page.on('download', …) handler for Files`, async ({ browser }) => { + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test(`should report download path within page.on('download', …) handler for Blobs`, async ({ browser }) => { + await browser.goto('/download-blob.html'); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test('should report alt-click downloads', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap({ modifiers: ['Alt'] })); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test('should report new window downloads', async ({ browser }) => { + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + }); + + test('should download large binary.zip', async ({ browser }) => { + const fileContent = Buffer.alloc(1 << 20); + for (let i = 0; i < fileContent.length; i++) fileContent[i] = Math.imul(i + 1, 2654435761) >>> 24; + await browser.goto('/empty.html'); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + const downloaded = fs.readFileSync(download.absolutePath); + expect(downloaded.byteLength).toBe(fileContent.byteLength); + expect(downloaded.equals(fileContent)).toBe(true); + }); + + test('should report downloads with interception', async ({ browser }) => { + await browser.route(/.*/, (route) => route.continue()); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); + + test('should emit download event from nested iframes', async ({ browser }) => { + const third = content(` download`); + const second = content(``); + await browser.goto(content(``)); + const download = await browser.waitForDownload(() => browser.frameLocator('iframe').frameLocator('iframe').locator('a').tap()); + expect(fs.existsSync(download.absolutePath)).toBeTruthy(); + expect(fs.readFileSync(download.absolutePath).toString()).toBe('Hello world'); + }); +}); + +test.describe('download', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should be able to download a PDF file', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content('download')); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + assertDownloadToPDF(download, asset('empty.pdf')); + }); + + test('should be able to download a inline PDF file via response interception', { fail: '`route.fulfill` bodies are strings, so binary bytes do not survive the round trip' }, async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.route('**/empty.pdf', async (route) => { + const response = await route.fetch(); + await route.fulfill({ + status: response.status, + headers: { ...response.headers, 'Content-Disposition': 'attachment' }, + body: await response.text(), + }); + }); + await browser.goto(content('open')); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + assertDownloadToPDF(download, asset('empty.pdf')); + }); + + test('should be able to download a inline PDF file via navigation', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content('open')); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + assertDownloadToPDF(download, asset('empty.pdf')); + }); + + test('should download even if there is no "attachment" value', async ({ browser }) => { + await browser.goto(content(`download`)); + await browser.waitForDownload(() => browser.locator('a').tap()); + }); + + test('should convert navigation to a resource with unsupported mime type into download', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto('/empty.html'); + await browser.waitForDownload(async () => { + await browser.goto(respond({ 'content-type': 'application/octet-stream' })).catch(() => undefined); + }); + }); + + test('should download links with data url', async ({ browser }) => { + await browser.goto(content('Download!')); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(download.suggestedFilename).toBe('SomeFile.txt'); + }); + + test('should download successfully when routing', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue()); + await browser.goto('/empty.html'); + await browser.goto(content(`download`)); + const download = await browser.waitForDownload(() => browser.locator('a').tap()); + expect(download.suggestedFilename).toBe('foo.zip'); + }); +}); diff --git a/apps/testbed/tests/elementhandle-scroll-into-view.e2e.ts b/apps/testbed/tests/elementhandle-scroll-into-view.e2e.ts new file mode 100644 index 0000000000..827bfb73ee --- /dev/null +++ b/apps/testbed/tests/elementhandle-scroll-into-view.e2e.ts @@ -0,0 +1,106 @@ +/** + * Adapted from microsoft/playwright tests/page/elementhandle-scroll-into-view.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: an element handle's + * `scrollIntoViewIfNeeded` is a locator `scrollIntoView`, its own `evaluate` + * a page `evaluate` on the same element. + * + * Not ported: + * - should throw for detached element: a handle to a removed element; a locator re-resolves. + */ + +import { test, type Browser } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +/** + * Starts scrolling the page's one `div` into view, checks it is still + * waiting a second later, runs `after` on the div in the page, and checks the + * scroll then finishes: Playwright's `testWaiting`. + */ +async function testWaiting(browser: Browser, after: string): Promise { + let done = false; + const promise = browser.locator('div').scrollIntoView().then(() => (done = true)); + await new Promise((resolve) => setTimeout(resolve, 1000)); + expect(done).toBe(false); + await browser.evaluate(`() => { const div = document.querySelector('div'); (${after})(div); }`); + await promise; + expect(done).toBe(true); +} + +test.describe('elementhandle scroll into view', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should work @smoke', async ({ browser }) => { + await browser.goto('/offscreenbuttons.html'); + const overflow = '(id) => document.getElementById(id).getBoundingClientRect().right - window.innerWidth'; + for (let i = 0; i < 11; ++i) { + const before = await browser.evaluate(overflow, `btn${i}`); + expect(before).toBe(10 * i); + await browser.locator(`#btn${i}`).scrollIntoView(); + const after = await browser.evaluate(overflow, `btn${i}`); + expect(after <= 0).toBe(true); + await browser.evaluate('() => window.scrollTo(0, 0)'); + } + }); + + test('should wait for display:none to become visible', async ({ browser }) => { + await browser.goto(content('
Hello
')); + await testWaiting(browser, "div => div.style.display = 'block'"); + }); + + test('should scroll display:contents into view', async ({ browser }) => { + await browser.goto(content(` + +
+
+
+
Hello
+
+
+
+ `)); + await browser.locator('#target').scrollIntoView(); + const scrollTop = await browser.evaluate("() => document.querySelector('#container').scrollTop"); + expect(Math.abs(scrollTop - 350)).toBeLessThan(1); + }); + + test('should work for visibility:hidden element', async ({ browser }) => { + await browser.goto(content('
Hello
')); + await browser.locator('div').scrollIntoView(); + }); + + test('should work for zero-sized element', async ({ browser }) => { + await browser.goto(content('
Hello
')); + await browser.locator('div').scrollIntoView(); + }); + + test('should wait for nested display:none to become visible', async ({ browser }) => { + await browser.goto(content('
Hello
')); + await testWaiting(browser, "div => div.parentElement.style.display = 'block'"); + }); + + test('should wait for element to stop moving', async ({ browser }) => { + await browser.goto(content(` + +
moving
+ `)); + await testWaiting(browser, "div => div.classList.remove('animated')"); + }); + + test('should timeout waiting for visible', async ({ browser }) => { + await browser.goto(content('
Hello
')); + const error = await browser.locator('div').scrollIntoView({ timeout: 3000 }).catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + }); +}); diff --git a/apps/testbed/tests/filechooser.e2e.ts b/apps/testbed/tests/filechooser.e2e.ts new file mode 100644 index 0000000000..98b4c26354 --- /dev/null +++ b/apps/testbed/tests/filechooser.e2e.ts @@ -0,0 +1,130 @@ +/** + * Adapted from microsoft/playwright tests/page/page-filechooser.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: a file chooser is answered by `setInputFiles` on the control whose + * click opens it, so the page's own `click()` on the input is a button that does it. + */ + +/* + * Not ported: + * - should emit event once: needs `page.once('filechooser')`. + * - should emit event via prepend: needs `page.prependListener('filechooser')`. + * - should emit event for iframe: needs `filechooser` events. + * - should emit event on/off: needs `page.on('filechooser')` and `page.off`. + * - should emit event addListener/removeListener: needs `page.addListener('filechooser')`. + * - should work when file input is attached to DOM: needs `page.waitForEvent('filechooser')`. + * - should not throw when filechooser belongs to iframe: needs `filechooser` events and `frame.setContent`. + * - should not throw when frame is detached immediately: needs `page.on('filechooser')` and `frame.setContent`. + * - should respect timeout: needs `page.waitForEvent('filechooser')`. + * - should respect default timeout when there is no custom timeout: needs `page.setDefaultTimeout`. + * - should prioritize exact timeout over default timeout: needs `page.setDefaultTimeout`. + * - should work with no timeout: needs `page.waitForEvent('filechooser', { timeout: 0 })`. + * - should abort with signal: needs `page.waitForEvent('filechooser', { signal })`. + * - should return the same file chooser when there are many watchdogs simultaneously: needs `FileChooser` objects. + * - should not trim big uploaded files: no file chooser; ported in page-set-input-files.e2e.ts. + * - should work for single file pick: needs `fileChooser.isMultiple()`. + * - should work for "multiple": needs `fileChooser.isMultiple()`. + * - should work for "webkitdirectory": needs `fileChooser.isMultiple()`. + * - should trigger listener added before navigation: needs `page.once('filechooser')`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { asset, content, CROSS, PREFIX } from './helpers.ts'; + +/** A button whose click clicks the page's file input, as `picker.click()` does in Playwright's tests. */ +const PICKER = ""; + +/** Resolves, in the page, with the first picked file's text once the input fires `input`. */ +const readPicked = `() => { + const picker = document.querySelector('input'); + window.picked = new Promise((x) => { picker.oninput = x; }).then(() => { + const reader = new FileReader(); + const promise = new Promise((fulfill) => { reader.onload = fulfill; }); + reader.readAsText(picker.files[0]); + return promise.then(() => reader.result); + }); +}`; + +test.describe('page filechooser', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should upload multiple large files', async ({ browser }) => { + const filesCount = 10; + await browser.goto('/input/fileupload-multi.html'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'e2e-chooser-')); + try { + const uploadFile = path.join(dir, '50MB_1.zip'); + const str = 'A'.repeat(1024); + const stream = fs.createWriteStream(uploadFile); + for (let i = 0; i < 49 * 1024; i++) { + await new Promise((fulfill, reject) => stream.write(str, (error) => (error ? reject(error) : fulfill()))); + } + await new Promise((fulfill) => stream.end(fulfill)); + const uploadFiles = [uploadFile]; + for (let i = 2; i <= filesCount; i++) { + const dstFile = path.join(dir, `50MB_${i}.zip`); + fs.copyFileSync(uploadFile, dstFile); + uploadFiles.push(dstFile); + } + await browser.evaluate("() => { const button = document.createElement('button'); button.textContent = 'pick'; button.type = 'button'; button.onclick = () => document.querySelector('input[type=\"file\"]').click(); document.body.append(button); }"); + await browser.locator('button').setInputFiles(uploadFiles); + const filesLen = await browser.evaluate('document.getElementsByTagName("input")[0].files.length'); + expect(filesLen).toEqual(filesCount); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + test('should work when file input is not attached to DOM', async ({ browser }) => { + await browser.goto(content(``)); + await browser.locator('button').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate('() => window.picked')).toBe('contents of the file'); + }); + + test('should accept single file', async ({ browser }) => { + await browser.goto(content("")); + await browser.locator('button').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate("() => document.querySelector('input').files.length")).toBe(1); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + }); + + test('should be able to read selected file', async ({ browser }) => { + await browser.goto(content(PICKER)); + await browser.evaluate(readPicked); + await browser.locator('button').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate('() => window.picked')).toBe('contents of the file'); + }); + + test('should be able to reset selected files with empty file list', { skip: '`setInputFiles([])` is refused, so there is no way to clear a file input (refused as INVALID_ARGUMENT, which `fail` does not cover)' }, async ({ browser }) => { + await browser.goto(content(PICKER)); + const watchLength = "() => { const picker = document.querySelector('input'); window.picked = new Promise((x) => { picker.oninput = x; }).then(() => picker.files.length); }"; + await browser.evaluate(watchLength); + await browser.locator('button').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate('() => window.picked')).toBe(1); + await browser.evaluate(watchLength); + await browser.locator('button').setInputFiles([]); + expect(await browser.evaluate('() => window.picked')).toBe(0); + }); + + test('should emit event after navigation', async ({ browser }) => { + await browser.goto(`${PREFIX}/empty.html`); + await browser.goto(content(PICKER)); + await browser.locator('button').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate("() => document.querySelector('input').files.length")).toBe(1); + await browser.goto(`${CROSS}/empty.html`); + await browser.goto(`${CROSS}${content(PICKER)}`); + await browser.locator('button').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate("() => document.querySelector('input').files.length")).toBe(1); + }); +}); diff --git a/apps/testbed/tests/fill.e2e.ts b/apps/testbed/tests/fill.e2e.ts new file mode 100644 index 0000000000..5c0ed04c40 --- /dev/null +++ b/apps/testbed/tests/fill.e2e.ts @@ -0,0 +1,369 @@ +/** + * Adapted from microsoft/playwright tests/page/page-fill.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `page.fill(selector, value)` is a locator fill. + */ + +/* + * Not ported: + * - should throw if passed a non-string value: asserts Playwright's protocol validator message for a number; `fill` is typed to strings. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +/** Five pairs of animation frames, Playwright's `rafraf(page, 5)`, so a pending fill has had its chance. */ +const giveItAChanceToFill = '() => new Promise((resolve) => { let frames = 0; const step = () => (++frames === 10 ? setTimeout(resolve, 0) : requestAnimationFrame(step)); requestAnimationFrame(step); })'; + +test.describe('page fill', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should fill textarea', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').fill('some value'); + expect(await browser.evaluate('result')).toBe('some value'); + }); + + test('should fill input', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('input').fill('some value'); + expect(await browser.evaluate('result')).toBe('some value'); + }); + + test('should throw on unsupported inputs', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + for (const type of ['button', 'checkbox', 'file', 'image', 'radio', 'reset', 'submit']) { + await browser.evaluate("(type) => document.querySelector('input').setAttribute('type', type)", type); + const error = await browser.locator('input').fill('').catch((caught: Error) => caught); + expect((error as Error).message).toContain(`Input of type "${type}" cannot be filled`); + } + }); + + test('should fill different input types', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + for (const type of ['password', 'search', 'tel', 'text', 'url', 'invalid-type']) { + await browser.evaluate("(type) => document.querySelector('input').setAttribute('type', type)", type); + await browser.locator('input').fill('text ' + type); + expect(await browser.evaluate('result')).toBe('text ' + type); + } + }); + + test('should fill range input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('42'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('42'); + }); + + test('should throw on incorrect range value', async ({ browser }) => { + await browser.goto(content('')); + const error1 = await browser.locator('input').fill('foo').catch((caught: Error) => caught); + expect((error1 as Error).message).toContain('Malformed value'); + const error2 = await browser.locator('input').fill('200').catch((caught: Error) => caught); + expect((error2 as Error).message).toContain('Malformed value'); + const error3 = await browser.locator('input').fill('15.43').catch((caught: Error) => caught); + expect((error3 as Error).message).toContain('Malformed value'); + }); + + test('should fill color input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('#aaaaaa'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('#aaaaaa'); + }); + + test('should fill color input case insensitive', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('#AbCd00'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('#abcd00'); + }); + + test('should throw on incorrect color value', async ({ browser }) => { + await browser.goto(content('')); + const error1 = await browser.locator('input').fill('badvalue').catch((caught: Error) => caught); + expect((error1 as Error).message).toContain('Malformed value'); + }); + + test('should fill date input after clicking', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').tap(); + await browser.locator('input').fill('2020-03-02'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('2020-03-02'); + }); + + for (const [type, value] of Object.entries({ + 'color': '#aaaaaa', + 'date': '2020-03-02', + 'time': '13:15', + 'datetime-local': '2020-03-02T13:15:30', + 'month': '2020-03', + 'range': '42', + 'week': '2020-W50', + })) { + test(`input event.composed should be true and cross shadow dom boundary - ${type}`, async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(``)); + await browser.evaluate(`() => { + window.firedBodyEvents = []; + for (const event of ['input', 'change']) + document.body.addEventListener(event, (e) => window.firedBodyEvents.push(e.type + ':' + e.composed), false); + }`); + await browser.evaluate(`() => { + window.firedEvents = []; + const input = document.querySelector('div').shadowRoot.querySelector('input'); + for (const event of ['input', 'change']) + input.addEventListener(event, (e) => window.firedEvents.push(e.type + ':' + e.composed), false); + }`); + await browser.locator('input').fill(value); + expect(await browser.evaluate('firedEvents')).toEqual(['input:true', 'change:false']); + expect(await browser.evaluate('firedBodyEvents')).toEqual(['input:true']); + }); + } + + test('should throw on incorrect date', async ({ browser }) => { + await browser.goto(content('')); + const error = await browser.locator('input').fill('2020-13-05').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Malformed value'); + }); + + test('should fill time input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('13:15'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('13:15'); + }); + + test('should fill month input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('2020-07'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('2020-07'); + }); + + test('should throw on incorrect month', async ({ browser }) => { + await browser.goto(content('')); + const error = await browser.locator('input').fill('2020-13').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Malformed value'); + }); + + test('should fill week input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('2020-W50'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('2020-W50'); + }); + + test('should throw on incorrect week', async ({ browser }) => { + await browser.goto(content('')); + const error = await browser.locator('input').fill('2020-123').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Malformed value'); + }); + + test('should throw on incorrect time', async ({ browser }) => { + await browser.goto(content('')); + const error = await browser.locator('input').fill('25:05').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Malformed value'); + }); + + test('should fill datetime-local input', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').fill('2020-03-02T05:15'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('2020-03-02T05:15'); + }); + + test('should throw on incorrect datetime-local', async ({ browser }) => { + await browser.goto(content('')); + const error = await browser.locator('input').fill('abc').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Malformed value'); + }); + + test('should fill contenteditable', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('div[contenteditable]').fill('some value'); + expect(await browser.evaluate("() => document.querySelector('div[contenteditable]').textContent")).toBe('some value'); + }); + + test('should fill contenteditable with new lines', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content('
')); + await browser.locator('div[contenteditable]').fill('John\nDoe'); + expect(await browser.evaluate("() => document.querySelector('div[contenteditable]').innerText")).toBe('John\nDoe'); + }); + + test('should not double-fill in contenteditable with beforeinput handler in Firefox', async ({ browser }) => { + await browser.goto(content(` +
+ + `)); + const locator = browser.locator('#editor'); + const testValue = 'Playwright'; + await locator.fill(testValue); + await expect(locator).toHaveText(testValue); + }); + + test('should fill elements with existing value and selection', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + + await browser.evaluate("() => { document.querySelector('input').value = 'value one'; }"); + await browser.locator('input').fill('another value'); + expect(await browser.evaluate('result')).toBe('another value'); + + await browser.evaluate("() => { const input = document.querySelector('input'); input.selectionStart = 1; input.selectionEnd = 2; }"); + await browser.locator('input').fill('maybe this one'); + expect(await browser.evaluate('result')).toBe('maybe this one'); + + await browser.evaluate(`() => { + const div = document.querySelector('div[contenteditable]'); + div.innerHTML = 'some text some more text and even more text'; + const range = document.createRange(); + range.selectNodeContents(div.querySelector('span')); + const selection = window.getSelection(); + selection.removeAllRanges(); + selection.addRange(range); + }`); + await browser.locator('div[contenteditable]').fill('replace with this'); + expect(await browser.evaluate("() => document.querySelector('div[contenteditable]').textContent")).toBe('replace with this'); + }); + + test('should throw nice error without injected script stack when element is not an ', async ({ browser }) => { + await browser.goto(content('')); + const error = await browser.locator('select').fill('').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Element is not an ,
')); + for (const locator of [browser.locator('input'), browser.locator('textarea'), browser.locator('div')]) { + await locator.focus(); + await browser.keyboard.press('Alt+KeyA'); + await browser.keyboard.press('Alt+Digit1'); + await browser.keyboard.press('Alt+Shift+KeyA'); + await browser.keyboard.down('Alt'); + await browser.keyboard.press('b'); + await browser.keyboard.up('Alt'); + await locator.press('c'); + } + await expect(browser.locator('input')).toHaveValue('c'); + await expect(browser.locator('textarea')).toHaveValue('c'); + await expect(browser.locator('div')).toHaveText('c'); + }); + + test('should emit keydown, keypress, textInput and input when typing a character', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate(`() => { + window.events = []; + for (const type of ['keydown', 'keypress', 'textInput', 'input', 'keyup']) + document.querySelector('input').addEventListener(type, () => window.events.push(type)); + }`); + await browser.locator('input').focus(); + await browser.keyboard.press('f'); + expect(await browser.evaluate('events')).toEqual(['keydown', 'keypress', 'textInput', 'input', 'keyup']); + }); + + test('should dispatch key events in separate tasks', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate(`() => { + 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.press('a'); + expect(await browser.evaluate('log')).toEqual(['keydown', 'microtask-keydown', 'keypress', 'microtask-keypress']); + }); + + test('should report shiftKey', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + const keyboard = browser.keyboard; + const codeForKey = { 'Shift': 16, 'Alt': 18, 'Control': 17 }; + for (const modifierKey in codeForKey) { + await keyboard.down(modifierKey); + expect(await browser.evaluate('getResult()')).toBe('Keydown: ' + modifierKey + ' ' + modifierKey + 'Left LEFT [' + modifierKey + ']'); + await keyboard.down('!'); + if (modifierKey === 'Shift') expect(await browser.evaluate('getResult()')).toBe('Keydown: ! Digit1 STANDARD [' + modifierKey + ']\nKeypress: ! Digit1 STANDARD 33 [' + modifierKey + ']'); + else expect(await browser.evaluate('getResult()')).toBe('Keydown: ! Digit1 STANDARD [' + modifierKey + ']'); + + await keyboard.up('!'); + expect(await browser.evaluate('getResult()')).toBe('Keyup: ! Digit1 STANDARD [' + modifierKey + ']'); + await keyboard.up(modifierKey); + expect(await browser.evaluate('getResult()')).toBe('Keyup: ' + modifierKey + ' ' + modifierKey + 'Left LEFT []'); + } + }); + + test('should report multiple modifiers', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + const keyboard = browser.keyboard; + await keyboard.down('Control'); + expect(await browser.evaluate('getResult()')).toBe('Keydown: Control ControlLeft LEFT [Control]'); + await keyboard.down('Alt'); + expect(await browser.evaluate('getResult()')).toBe('Keydown: Alt AltLeft LEFT [Alt Control]'); + await keyboard.down(';'); + expect(await browser.evaluate('getResult()')).toBe('Keydown: ; Semicolon STANDARD [Alt Control]'); + await keyboard.up(';'); + expect(await browser.evaluate('getResult()')).toBe('Keyup: ; Semicolon STANDARD [Alt Control]'); + await keyboard.up('Control'); + expect(await browser.evaluate('getResult()')).toBe('Keyup: Control ControlLeft LEFT [Alt]'); + await keyboard.up('Alt'); + expect(await browser.evaluate('getResult()')).toBe('Keyup: Alt AltLeft LEFT []'); + }); + + test('should send proper codes while typing', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.type('!'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: ! Digit1 STANDARD []', + 'Keypress: ! Digit1 STANDARD 33 []', + 'Keyup: ! Digit1 STANDARD []'].join('\n')); + await browser.keyboard.type('^'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: ^ Digit6 STANDARD []', + 'Keypress: ^ Digit6 STANDARD 94 []', + 'Keyup: ^ Digit6 STANDARD []'].join('\n')); + }); + + test('should send proper codes while typing with shift', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + const keyboard = browser.keyboard; + await keyboard.down('Shift'); + await browser.keyboard.type('~'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: Shift ShiftLeft LEFT [Shift]', + 'Keydown: ~ Backquote STANDARD [Shift]', + 'Keypress: ~ Backquote STANDARD 126 [Shift]', + 'Keyup: ~ Backquote STANDARD [Shift]'].join('\n')); + await keyboard.up('Shift'); + }); + + test('should not type canceled events', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').focus(); + await browser.evaluate(`() => { + window.addEventListener('keydown', (event) => { + event.stopPropagation(); + event.stopImmediatePropagation(); + if (event.key === 'l') + event.preventDefault(); + if (event.key === 'o') + event.preventDefault(); + }, false); + }`); + await browser.keyboard.type('Hello World!'); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe('He Wrd!'); + }); + + test('should press plus', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('+'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: + Equal STANDARD []', + 'Keypress: + Equal STANDARD 43 []', + 'Keyup: + Equal STANDARD []'].join('\n')); + }); + + test('should press shift plus', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('Shift++'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: Shift ShiftLeft LEFT [Shift]', + 'Keydown: + Equal STANDARD [Shift]', + 'Keypress: + Equal STANDARD 43 [Shift]', + 'Keyup: + Equal STANDARD [Shift]', + 'Keyup: Shift ShiftLeft LEFT []'].join('\n')); + }); + + test('should support plus-separated modifiers', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('Shift+~'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: Shift ShiftLeft LEFT [Shift]', + 'Keydown: ~ Backquote STANDARD [Shift]', + 'Keypress: ~ Backquote STANDARD 126 [Shift]', + 'Keyup: ~ Backquote STANDARD [Shift]', + 'Keyup: Shift ShiftLeft LEFT []'].join('\n')); + }); + + test('should support multiple plus-separated modifiers', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('Control+Shift+~'); + expect(await browser.evaluate('getResult()')).toBe( + ['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 []'].join('\n')); + }); + + test('should shift raw codes', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('Shift+Digit3'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: Shift ShiftLeft LEFT [Shift]', + 'Keydown: # Digit3 STANDARD [Shift]', + 'Keypress: # Digit3 STANDARD 35 [Shift]', + 'Keyup: # Digit3 STANDARD [Shift]', + 'Keyup: Shift ShiftLeft LEFT []'].join('\n')); + }); + + test('should specify repeat property', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').focus(); + await browser.evaluate(captureLastKeydown); + await browser.keyboard.down('a'); + expect(await browser.evaluate('lastEvent.repeat')).toBe(false); + await browser.keyboard.press('a'); + expect(await browser.evaluate('lastEvent.repeat')).toBe(true); + + await browser.keyboard.down('b'); + expect(await browser.evaluate('lastEvent.repeat')).toBe(false); + await browser.keyboard.down('b'); + expect(await browser.evaluate('lastEvent.repeat')).toBe(true); + + await browser.keyboard.up('a'); + await browser.keyboard.down('a'); + expect(await browser.evaluate('lastEvent.repeat')).toBe(false); + }); + + test('should type all kinds of characters', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').focus(); + const text = 'This text goes onto two lines.\nThis character is 嗨.'; + await browser.keyboard.type(text); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe(text); + }); + + test('should specify location', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.evaluate(captureLastKeydown); + const textarea = browser.locator('textarea'); + + await textarea.focus(); + await browser.keyboard.press('Digit5'); + expect.soft(await browser.evaluate('lastEvent.location')).toBe(0); + expect.soft(await browser.evaluate('lastEvent.key')).toBe('5'); + expect.soft(await browser.evaluate('lastEvent.code')).toBe('Digit5'); + + await textarea.focus(); + await browser.keyboard.press('ControlLeft'); + expect.soft(await browser.evaluate('lastEvent.location')).toBe(1); + expect.soft(await browser.evaluate('lastEvent.key')).toBe('Control'); + expect.soft(await browser.evaluate('lastEvent.code')).toBe('ControlLeft'); + + await textarea.focus(); + await browser.keyboard.press('ControlRight'); + expect.soft(await browser.evaluate('lastEvent.location')).toBe(2); + expect.soft(await browser.evaluate('lastEvent.key')).toBe('Control'); + expect.soft(await browser.evaluate('lastEvent.code')).toBe('ControlRight'); + + await textarea.focus(); + await browser.keyboard.press('NumpadSubtract'); + expect.soft(await browser.evaluate('lastEvent.location')).toBe(3); + expect.soft(await browser.evaluate('lastEvent.key')).toBe('-'); + expect.soft(await browser.evaluate('lastEvent.code')).toBe('NumpadSubtract'); + }); + + test('should specify numpad location on keyup', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('NumpadSubtract'); + expect(await browser.evaluate('getResult()')).toBe( + ['Keydown: - NumpadSubtract NUMPAD []', + 'Keypress: - NumpadSubtract NUMPAD 45 []', + 'Keyup: - NumpadSubtract NUMPAD []'].join('\n')); + }); + + test('should press NumpadDecimal as Delete', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate(captureLastKeydown); + const textarea = browser.locator('textarea'); + + await textarea.focus(); + await browser.keyboard.press('NumpadDecimal'); + expect(await browser.evaluate('lastEvent.key')).toBe('Delete'); + expect(await browser.evaluate('lastEvent.code')).toBe('NumpadDecimal'); + expect(await browser.evaluate('lastEvent.location')).toBe(3); + await expect(textarea).toHaveValue(''); + }); + + test('should type numpad digits with Shift', async ({ browser }) => { + await browser.goto(content('')); + const textarea = browser.locator('textarea'); + await textarea.focus(); + await browser.keyboard.press('Shift+Numpad1'); + await browser.keyboard.press('Shift+NumpadDecimal'); + await browser.keyboard.press('Shift+Numpad9'); + await expect(textarea).toHaveValue('1.9'); + }); + + test('should press Enter', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('textarea').focus(); + await browser.evaluate(captureLastKeydown); + for (const [key, expectedKey, expectedCode] of [ + ['Enter', 'Enter', 'Enter'], + ['NumpadEnter', 'Enter', 'NumpadEnter'], + ['\n', 'Enter', 'Enter'], + ['\r', 'Enter', 'Enter'], + ] as const) { + await browser.keyboard.press(key); + expect(await browser.evaluate('lastEvent.key')).toBe(expectedKey); + expect(await browser.evaluate('lastEvent.code')).toBe(expectedCode); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe('\n'); + await browser.evaluate("() => { document.querySelector('textarea').value = ''; }"); + } + }); + + test('should press audio and media control keys', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input').focus(); + await browser.evaluate(captureLastKeydown); + const mediaKeys = [ + { key: 'AudioVolumeMute', code: 'AudioVolumeMute' }, + { key: 'AudioVolumeDown', code: 'AudioVolumeDown' }, + { key: 'AudioVolumeUp', code: 'AudioVolumeUp' }, + { key: 'MediaTrackNext', code: 'MediaTrackNext' }, + { key: 'MediaTrackPrevious', code: 'MediaTrackPrevious' }, + { key: 'MediaPlayPause', code: 'MediaPlayPause' }, + ]; + for (const mediaKey of mediaKeys) { + await browser.keyboard.press(mediaKey.key); + expect.soft(await browser.evaluate('lastEvent.key')).toBe(mediaKey.key); + expect.soft(await browser.evaluate('lastEvent.code')).toBe(mediaKey.code); + expect.soft(await browser.evaluate('lastEvent.location')).toBe(0); + } + }); + + test('should throw on unknown keys', async ({ browser }) => { + await browser.goto('/empty.html'); + let error = await browser.keyboard.press('NotARealKey').catch((caught: Error) => caught); + expect((error as Error).message).toContain('Unknown key: "NotARealKey"'); + + error = await browser.keyboard.press('ё').catch((caught: Error) => caught); + expect(error && (error as Error).message).toContain('Unknown key: "ё"'); + + error = await browser.keyboard.press('😊').catch((caught: Error) => caught); + expect(error && (error as Error).message).toContain('Unknown key: "😊"'); + }); + + test('should type emoji', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').pressSequentially('👹 Tokyo street Japan 🇯🇵'); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe('👹 Tokyo street Japan 🇯🇵'); + }); + + test('should type emoji into an iframe', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate(`() => 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').pressSequentially('👹 Tokyo street Japan 🇯🇵'); + expect(await browser.evaluate("() => document.querySelector('#emoji-test').contentDocument.querySelector('textarea').value")).toBe('👹 Tokyo street Japan 🇯🇵'); + }); + + test('should handle selectAll', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').pressSequentially('some text'); + await browser.keyboard.down('ControlOrMeta'); + await browser.keyboard.press('a'); + await browser.keyboard.up('ControlOrMeta'); + await browser.keyboard.press('Backspace'); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe(''); + }); + + test('pressing Meta should not result in any text insertion on any platform', async ({ browser }) => { + await browser.goto(content('')); + const input = browser.locator('input'); + await expect(input).toHaveValue('hello world'); + await input.focus(); + await browser.keyboard.press('Meta'); + await expect(input).toHaveValue('hello world'); + }); + + test('should be able to prevent selectAll', async ({ browser }) => { + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').pressSequentially('some text'); + await browser.evaluate(`() => { + document.querySelector('textarea').addEventListener('keydown', (event) => { + if (event.key === 'a' && (event.metaKey || event.ctrlKey)) + event.preventDefault(); + }, false); + }`); + await browser.keyboard.down('ControlOrMeta'); + await browser.keyboard.press('a'); + await browser.keyboard.up('ControlOrMeta'); + await browser.keyboard.press('Backspace'); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe('some tex'); + }); + + test('should support MacOS shortcuts', async ({ browser }) => { + test.skip(!isMac); + await browser.goto('/input/textarea.html'); + await browser.locator('textarea').pressSequentially('some text'); + await browser.keyboard.press('Shift+Control+Alt+KeyB'); + await browser.keyboard.press('Backspace'); + expect(await browser.evaluate("() => document.querySelector('textarea').value")).toBe('some '); + }); + + test('should press the meta key', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate(captureLastKeydown); + await browser.keyboard.press('Meta'); + const { key, code, metaKey } = await browser.evaluate<{ key: string; code: string; metaKey: boolean }>('lastEvent'); + expect(key).toBe('Meta'); + expect(code).toBe('MetaLeft'); + expect(metaKey).toBe(true); + }); + + test('should work with keyboard events with empty.html', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate(captureLastKeydown); + await browser.keyboard.press('a'); + expect(await browser.evaluate('lastEvent.key')).toBe('a'); + }); + + test('should work after a cross origin navigation', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(`${CROSS}/empty.html`); + await browser.evaluate(captureLastKeydown); + await browser.keyboard.press('a'); + expect(await browser.evaluate('lastEvent.key')).toBe('a'); + }); + + test('should scroll with PageDown', async ({ browser }) => { + await browser.goto('/input/scrollable.html'); + await browser.locator('body').tap(); + await browser.keyboard.press('PageDown'); + await expect.poll(() => browser.evaluate('scrollY > 0')).toBe(true); + }); + + test('should move around the selection in a contenteditable', async ({ browser }) => { + await browser.goto(content('
')); + await browser.locator('div').focus(); + const modifier = isMac ? 'Alt' : 'Control'; + await browser.keyboard.type('Hello World'); + await browser.keyboard.down(modifier); + await browser.keyboard.down('Shift'); + await browser.keyboard.press('ArrowLeft'); + await browser.keyboard.up('Shift'); + await browser.keyboard.up(modifier); + expect(await browser.evaluate('() => window.getSelection().toString()')).toBe('World'); + }); + + test('should move to the start of the document', async ({ browser }) => { + test.skip(!isMac); + await browser.goto(content('
')); + await browser.locator('div').focus(); + await browser.keyboard.type('1\n2\n3\n'); + await browser.keyboard.press('Shift+Meta+ArrowUp'); + expect(await browser.evaluate('() => window.getSelection().toString()')).toBe('1\n2\n3\n'); + }); + + test('should dispatch a click event on a button when Space gets pressed', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate("() => { window.actual = { clicked: false }; document.querySelector('button').addEventListener('click', () => (window.actual.clicked = true)); }"); + await browser.locator('button').focus(); + await browser.keyboard.press('Space'); + expect(await browser.evaluate('actual.clicked')).toBe(true); + }); + + test('should dispatch a click event on a button when Enter gets pressed', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate("() => { window.actual = { clicked: false }; document.querySelector('button').addEventListener('click', () => (window.actual.clicked = true)); }"); + await browser.locator('button').focus(); + await browser.keyboard.press('Enter'); + expect(await browser.evaluate('actual.clicked')).toBe(true); + }); + + test('should support simple copy-pasting', async ({ browser }) => { + await browser.goto(content('
123
')); + await browser.locator('div').focus(); + await browser.keyboard.press('ControlOrMeta+KeyA'); + await browser.keyboard.press('ControlOrMeta+KeyC'); + await browser.keyboard.press('ControlOrMeta+KeyV'); + await browser.keyboard.press('ControlOrMeta+KeyV'); + expect(await browser.evaluate("() => document.querySelector('div').textContent")).toBe('123123'); + }); + + test('should support simple cut-pasting', async ({ browser }) => { + await browser.goto(content('
123
')); + await browser.locator('div').focus(); + await browser.keyboard.press('ControlOrMeta+KeyA'); + await browser.keyboard.press('ControlOrMeta+KeyX'); + await browser.keyboard.press('ControlOrMeta+KeyV'); + await browser.keyboard.press('ControlOrMeta+KeyV'); + expect(await browser.evaluate("() => document.querySelector('div').textContent")).toBe('123123'); + }); + + test('should support undo-redo', async ({ browser }) => { + await browser.goto(content('
')); + const div = browser.locator('div'); + await expect(div).toHaveText(''); + await div.pressSequentially('123'); + await expect(div).toHaveText('123'); + await browser.keyboard.press('ControlOrMeta+KeyZ'); + await expect(div).toHaveText(''); + await browser.keyboard.press('Shift+ControlOrMeta+KeyZ'); + await expect(div).toHaveText('123'); + }); + + test('should type repeatedly in contenteditable in shadow dom', async ({ browser }) => { + await browser.goto(content(` + + + + + + + `)); + + const editor = browser.locator('shadow-element > .editor').first(); + await editor.pressSequentially('This is the first box.'); + + const sectionEditor = browser.locator('section .editor'); + await sectionEditor.pressSequentially('This is the second box.'); + + expect(await editor.textContent()).toBe('This is the first box.'); + expect(await sectionEditor.textContent()).toBe('This is the second box.'); + }); + + test('should type repeatedly in contenteditable in shadow dom with nested elements', async ({ browser }) => { + await browser.goto(content(` + + + + + + + `)); + + const editor = browser.locator('shadow-element > .editor').first(); + await editor.pressSequentially('This is the first box: '); + + const sectionEditor = browser.locator('section .editor'); + await sectionEditor.pressSequentially('This is the second box: '); + + expect(await editor.textContent()).toBe('This is the first box: hello'); + expect(await sectionEditor.textContent()).toBe('This is the second box: world'); + }); + + test('should type repeatedly in input in shadow dom', async ({ browser }) => { + await browser.goto(content(` + + + + + + + `)); + + const editor = browser.locator('shadow-element > .editor').first(); + await editor.pressSequentially('This is the first box.'); + + const sectionEditor = browser.locator('section .editor'); + await sectionEditor.pressSequentially('This is the second box.'); + + expect(await editor.inputValue()).toBe('This is the first box.'); + expect(await sectionEditor.inputValue()).toBe('This is the second box.'); + }); + + test('type to non-focusable element should maintain old focus', async ({ browser }) => { + await browser.goto(content(` +
focusable div
+
non-editable, non-focusable
+ `)); + + await browser.locator('#focusable').focus(); + expect(await browser.evaluate('() => document.activeElement?.id')).toBe('focusable'); + await browser.locator('#non-focusable-and-non-editable').pressSequentially('foo'); + expect(await browser.evaluate('() => document.activeElement?.id')).toBe('focusable'); + }); + + test('should have correct Keydown/Keyup order when pressing Escape key', async ({ browser }) => { + await browser.goto('/input/keyboard.html'); + await browser.keyboard.press('Escape'); + expect(await browser.evaluate('getResult()')).toBe(` +Keydown: Escape Escape STANDARD [] +Keyup: Escape Escape STANDARD [] +`.trim()); + }); + + test('should close dialog on Escape key press in contenteditable', async ({ browser }) => { + await browser.goto(content(` + +
Edit Me
+
+ `)); + const widget = browser.locator('dialog [contenteditable]'); + await browser.evaluate("() => document.querySelector('dialog').showModal()"); + await expect.poll(() => browser.evaluate("() => document.querySelector('dialog').open")).toBe(true); + await expect(widget).toBeVisible(); + + await widget.press('Escape'); + await expect.poll(() => browser.evaluate("() => document.querySelector('dialog').open")).toBe(false); + await expect(widget).not.toBeVisible(); + }); +}); diff --git a/apps/testbed/tests/locator-convenience.e2e.ts b/apps/testbed/tests/locator-convenience.e2e.ts new file mode 100644 index 0000000000..48cdd0d1aa --- /dev/null +++ b/apps/testbed/tests/locator-convenience.e2e.ts @@ -0,0 +1,104 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-convenience.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: the `page.(selector)` twins of + * each locator read are locator reads, a `:text("...")` selector is + * `getByText`, and an element's own `evaluate` is a page `evaluate`. + * + * Not ported: + * - should have a nice preview: locator string previews and `evaluateHandle`. + * - innerHTML should work: e2e has no innerHTML. + * - innerText should work: e2e has no innerText. + * - innerText should throw: same. + * - innerText should produce log: same. + * - isEditable should work: e2e has no isEditable. + * - allInnerTexts should work: e2e has no allInnerTexts. + * - should return page: e2e locators have no page(). + * - description should return null for locator without description: e2e has no describe(). + * - description should return description for locator with simple description: same. + * - description should return description with special characters: same. + * - description should return description for chained locators: same. + * - description should return description for locator with multiple describe calls: same. + * - toString() returns formatted locator: e2e locators have no Playwright toString(). + * - toString() prefers description: same. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('locator convenience', { requires: ['browser'], tags: ['playwright'] }, () => { + test('getAttribute should work', async ({ browser }) => { + await browser.goto('/dom.html'); + const locator = browser.locator('#outer'); + expect(await locator.getAttribute('name')).toBe('value'); + expect(await locator.getAttribute('foo')).toBe(null); + }); + + test('inputValue should work', { fail: '`inputValue()` on an element that is no input reads "" instead of throwing' }, async ({ browser }) => { + await browser.goto('/dom.html'); + + await browser.locator('#select').selectOption({ value: 'foo' }); + expect(await browser.locator('#select').inputValue()).toBe('foo'); + + await browser.locator('#textarea').fill('text value'); + expect(await browser.locator('#textarea').inputValue()).toBe('text value'); + + await browser.locator('#input').fill('input value'); + expect(await browser.locator('#input').inputValue()).toBe('input value'); + + const error = await browser.locator('#inner').inputValue().catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + }); + + test('textContent should work', { fail: '`textContent()` normalizes whitespace, where Playwright keeps the raw text' }, async ({ browser }) => { + await browser.goto('/dom.html'); + const locator = browser.locator('#inner'); + expect(await locator.textContent()).toBe('Text,\nmore text'); + }); + + test('isEnabled and isDisabled should work', async ({ screen, browser }) => { + await browser.goto(content(` + + +
div
+ `)); + const div = browser.locator('div'); + expect(await div.isEnabled()).toBe(true); + expect(await div.isDisabled()).toBe(false); + const button1 = screen.getByText('button1', { exact: false }); + expect(await button1.isEnabled()).toBe(false); + expect(await button1.isDisabled()).toBe(true); + const button2 = screen.getByText('button2', { exact: false }); + expect(await button2.isEnabled()).toBe(true); + expect(await button2.isDisabled()).toBe(false); + }); + + test('isChecked should work', { fail: '`isChecked()` on an element that is no checkbox reads false instead of throwing' }, async ({ browser }) => { + await browser.goto(content(`
Not a checkbox
`)); + const element = browser.locator('input'); + expect(await element.isChecked()).toBe(true); + await browser.evaluate("() => { document.querySelector('input').checked = false; }"); + expect(await element.isChecked()).toBe(false); + const error = await browser.locator('div').isChecked().catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + }); + + test('isChecked should work for indeterminate input', async ({ browser }) => { + await browser.goto(content(``)); + await browser.evaluate("() => { document.querySelector('input').indeterminate = true; }"); + + expect(await browser.locator('input').isChecked()).toBe(true); + await expect(browser.locator('input')).toBeChecked(); + + await browser.locator('input').uncheck(); + + expect(await browser.locator('input').isChecked()).toBe(false); + await expect(browser.locator('input')).not.toBeChecked(); + }); + + test('allTextContents should work', async ({ browser }) => { + await browser.goto(content(`
A
B
C
`)); + expect(await browser.locator('div').allTextContents()).toEqual(['A', 'B', 'C']); + }); +}); diff --git a/apps/testbed/tests/locator-frame.e2e.ts b/apps/testbed/tests/locator-frame.e2e.ts new file mode 100644 index 0000000000..94c1d93991 --- /dev/null +++ b/apps/testbed/tests/locator-frame.e2e.ts @@ -0,0 +1,229 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-frame.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: the routed frame pages are pages the server serves (`content()`). + */ + +/* + * Not ported: + * - should wait for frame: asserts Playwright's `locator('body').locator('iframe').contentFrame()` log text; e2e has no locator.frameLocator. + * - should non work for non-frame: asserts Playwright's error text naming the matched `
`; e2e reports its own. + * - locator.frameLocator should work for iframe: e2e has no locator.frameLocator. + * - locator.frameLocator should throw on ambiguity: e2e has no locator.frameLocator. + * - locator.frameLocator should not throw on first/last/nth: e2e frame locators have no first/last/nth. + * - getBy coverage: e2e has no getByAltText or getByTitle; the other queries are kept as `getBy coverage (role, text, test id, label, placeholder)`. + * - should work with COEP/COOP/CORP isolated iframe: needs an https cross origin and page.frames(). + * - locator.contentFrame should work: e2e has no locator.contentFrame. + * - frameLocator.owner should work: e2e has no frameLocator.owner. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, CROSS } from './helpers.ts'; + +const nested = content(''); + +const iframe = content(` + +
+ + +
+ 1 + 2 + + `); + +const routed = content(``); + +/** Waits `ms` milliseconds. */ +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +test.describe('locator frame', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should work for iframe', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button'); + await button.waitFor(); + expect(await button.textContent()).toBe('Hello iframe'); + await expect(button).toHaveText('Hello iframe'); + await button.tap(); + }); + + test('should work for nested iframe', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').frameLocator('iframe').locator('button'); + await button.waitFor(); + expect(await button.textContent()).toBe('Hello nested iframe'); + await expect(button).toHaveText('Hello nested iframe'); + await button.tap(); + }); + + test('should work for $ and $$', async ({ browser }) => { + await browser.goto(routed); + const locator = browser.frameLocator('iframe').locator('button'); + await expect(locator).toHaveText('Hello iframe'); + const spans = browser.frameLocator('iframe').locator('span'); + await expect(spans).toHaveCount(2); + }); + + test('should wait for frame 2', async ({ browser }) => { + await browser.goto('about:blank'); + const navigated = delay(300).then(() => browser.goto(routed)); + await browser.frameLocator('iframe').locator('button').tap(); + await navigated; + }); + + test('should wait for frame to go', async ({ browser }) => { + await browser.goto(routed); + const removed = delay(300).then(() => browser.evaluate("() => { document.querySelector('iframe').remove(); }")); + await expect(browser.frameLocator('iframe').locator('button')).toBeHidden(); + await removed; + }); + + test('should not wait for frame', async ({ browser }) => { + await browser.goto('/empty.html'); + await expect(browser.frameLocator('iframe').locator('span')).toBeHidden(); + }); + + test('should not wait for frame 2', async ({ browser }) => { + await browser.goto('/empty.html'); + await expect(browser.frameLocator('iframe').locator('span')).not.toBeVisible(); + }); + + test('should not wait for frame 3', async ({ browser }) => { + await browser.goto('/empty.html'); + await expect(browser.frameLocator('iframe').locator('span')).toHaveCount(0); + }); + + test('should click in lazy iframe', async ({ browser }) => { + const lazy = content(''); + await browser.goto('/empty.html'); + const attached = delay(500) + .then(() => browser.evaluate("() => { document.body.appendChild(document.createElement('iframe')); }")) + .then(() => delay(500)) + .then(() => browser.evaluate("(src) => { document.querySelector('iframe').src = src; }", lazy)); + const button = browser.frameLocator('iframe').locator('button'); + const [, text] = await Promise.all([ + button.tap(), + button.textContent(), + expect(button).toHaveText('Hello iframe'), + attached, + ]); + expect(text).toBe('Hello iframe'); + }); + + test('waitFor should survive frame reattach', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.waitFor(); + await browser.evaluate("() => { document.querySelector('iframe').remove(); }"); + await browser.evaluate("(src) => { const iframe = document.createElement('iframe'); iframe.src = src; document.body.appendChild(iframe); }", nested); + await promise; + }); + + test('click should survive frame reattach', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.tap(); + await browser.evaluate("() => { document.querySelector('iframe').remove(); }"); + await browser.evaluate("(src) => { const iframe = document.createElement('iframe'); iframe.src = src; document.body.appendChild(iframe); }", nested); + await promise; + }); + + test('click should survive iframe navigation', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.tap(); + const navigated = browser.evaluate("(src) => { document.querySelector('iframe').src = src; }", nested); + await promise; + await navigated; + }); + + test('getBy coverage (role, text, test id, label, placeholder)', async ({ browser }) => { + await browser.goto(routed); + const button1 = browser.frameLocator('iframe').getByRole('button'); + const button2 = browser.frameLocator('iframe').getByText('Hello', { exact: false }); + const button3 = browser.frameLocator('iframe').getByTestId('buttonId'); + await expect(button1).toHaveText('Hello iframe'); + await expect(button2).toHaveText('Hello iframe'); + await expect(button3).toHaveText('Hello iframe'); + const input1 = browser.frameLocator('iframe').getByLabel('Name'); + await expect(input1).toHaveValue(''); + const input2 = browser.frameLocator('iframe').getByPlaceholder('Placeholder'); + await expect(input2).toHaveValue(''); + }); + + test('wait for hidden should succeed when frame is not in dom', async ({ browser }) => { + await browser.goto('about:blank'); + const button = browser.frameLocator('iframe1').locator('button'); + expect(await button.isHidden()).toBeTruthy(); + await button.waitFor({ state: 'hidden', timeout: 1000 }); + await button.waitFor({ state: 'detached', timeout: 1000 }); + const error = await button.waitFor({ state: 'attached', timeout: 1000 }).catch((caught: unknown) => caught); + expect(error).toBeDefined(); + }); + + test('should treat elements inside hidden iframe as hidden', { fail: 'the visibility read does not count an element inside a `visibility: hidden` iframe as hidden' }, async ({ browser }) => { + await browser.goto(content(` + +
+ + +
+ + `)); + + for (const button of [ + browser.frameLocator('[name=hidden]').locator('button'), + browser.frameLocator('[name=hidden-parent]').locator('button'), + browser.frameLocator('[name=outer]').frameLocator('[name=inner]').locator('button'), + ]) { + await expect(button).toBeAttached(); + expect(await button.isVisible()).toBe(false); + expect(await button.isHidden()).toBe(true); + await expect(button).toBeHidden(); + await expect(button).not.toBeVisible(); + await button.waitFor({ state: 'hidden' }); + } + + const button = browser.frameLocator('[name=visible-override]').locator('button'); + expect(await button.isVisible()).toBe(true); + await expect(button).toBeVisible(); + await button.waitFor({ state: 'visible' }); + }); + + test('should wait for hidden iframe to become visible', { fail: 'the visibility read does not count an element inside a `visibility: hidden` iframe as hidden' }, async ({ browser }) => { + await browser.goto(content(``)); + const button = browser.frameLocator('[name=frame]').locator('button'); + await expect(button).toBeHidden(); + + const error = await button.tap({ timeout: 1000 }).catch((caught: unknown) => caught); + expect(error).toBeDefined(); + expect(await browser.evaluate("() => document.querySelector('iframe').contentWindow.__clicked === true")).toBe(false); + + const clickPromise = button.tap(); + const visiblePromise = expect(button).toBeVisible(); + await browser.evaluate("() => { document.querySelector('iframe').style.visibility = 'visible'; }"); + await Promise.all([clickPromise, visiblePromise]); + expect(await browser.evaluate("() => document.querySelector('iframe').contentWindow.__clicked")).toBe(true); + + await browser.evaluate("() => { document.querySelector('iframe').style.visibility = 'hidden'; }"); + await expect(button).toBeHidden(); + expect(await button.isVisible()).toBe(false); + }); + + test('should treat elements inside hidden cross-origin iframe as hidden', { fail: 'the visibility read does not count an element inside a `visibility: hidden` iframe as hidden' }, async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(``)); + const div = browser.frameLocator('iframe').locator('div'); + await expect(div).toHaveText(`Hi, I'm frame`); + expect(await div.isVisible()).toBe(false); + await expect(div).toBeHidden(); + + await browser.evaluate("() => { document.querySelector('iframe').style.visibility = 'visible'; }"); + await expect(div).toBeVisible(); + expect(await div.isVisible()).toBe(true); + }); +}); diff --git a/apps/testbed/tests/locator-is-visible.e2e.ts b/apps/testbed/tests/locator-is-visible.e2e.ts new file mode 100644 index 0000000000..b726fa3af1 --- /dev/null +++ b/apps/testbed/tests/locator-is-visible.e2e.ts @@ -0,0 +1,137 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-is-visible.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: the `page.isVisible(selector)` twins + * of each locator read are locator reads, `locator(css, { hasText })` a + * locator `filter({ hasText })`. + * + * Not ported: + * - isVisible with invalid selector should throw: Playwright selector engine names. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('locator is visible', { requires: ['browser'], tags: ['playwright'] }, () => { + test('isVisible and isHidden should work', async ({ browser }) => { + await browser.goto(content(`
Hi
`)); + + const div = browser.locator('div'); + expect(await div.isVisible()).toBe(true); + expect(await div.isHidden()).toBe(false); + + const span = browser.locator('span'); + expect(await span.isVisible()).toBe(false); + expect(await span.isHidden()).toBe(true); + + expect(await browser.locator('no-such-element').isVisible()).toBe(false); + expect(await browser.locator('no-such-element').isHidden()).toBe(true); + }); + + test('isVisible should be true for opacity:0', async ({ browser }) => { + await browser.goto(content(`
Hi
`)); + await expect(browser.locator('div')).toBeVisible(); + }); + + test('isVisible should be true for element outside view', async ({ browser }) => { + await browser.goto(content(`
Hi
`)); + await expect(browser.locator('div')).toBeVisible(); + }); + + test('isVisible and isHidden should work with details', async ({ browser }) => { + await browser.goto(content(`
+ click to open +
    +
  • hidden item 1
  • +
  • hidden item 2
  • +
  • hidden item 3
  • +
`)); + + await expect(browser.locator('ul')).toBeHidden(); + }); + + test('isVisible and isHidden should work with nested details', async ({ screen, browser }) => { + await browser.goto(content(`
+ outer +
+ inner + +
+
`)); + + await expect(browser.locator('summary').filter({ hasText: 'outer' })).toBeVisible(); + await expect(browser.locator('summary').filter({ hasText: 'inner' })).toBeHidden(); + await expect(browser.locator('button')).toBeHidden(); + await expect(screen.getByRole('button')).toHaveCount(0); + }); + + test('isVisible and isHidden should work with unslotted content', async ({ browser }) => { + await browser.goto(content(` +
hidden 1
hidden 2
+
visible
+ + `)); + + await expect(browser.locator('span').filter({ hasText: 'hidden 1' })).toBeHidden(); + await expect(browser.locator('span').filter({ hasText: 'hidden 2' })).toBeHidden(); + await expect(browser.locator('span').filter({ hasText: 'visible' })).toBeVisible(); + }); + + test('isVisible and isHidden should work with list box options', async ({ screen, browser }) => { + await browser.goto(content(` + + + + `)); + + for (const name of ['visible 1', 'visible 2', 'visible 3']) + await expect(screen.getByRole('option', { name })).toBeVisible(); + for (const text of ['hidden 1', 'hidden 2', 'hidden 3']) + await expect(browser.locator('option').filter({ hasText: text })).toBeHidden(); + }); + + test('isVisible inside a button', async ({ browser }) => { + await browser.goto(content(``)); + const span = browser.locator('span'); + expect(await span.isVisible()).toBe(false); + expect(await span.isHidden()).toBe(true); + await expect(span).not.toBeVisible(); + await expect(span).toBeHidden(); + await span.waitFor({ state: 'hidden' }); + await browser.locator('button').waitFor({ state: 'visible' }); + }); + + test('isVisible inside a role=button', async ({ browser }) => { + await browser.goto(content(`
a button
`)); + const span = browser.locator('span'); + expect(await span.isVisible()).toBe(false); + expect(await span.isHidden()).toBe(true); + await expect(span).not.toBeVisible(); + await expect(span).toBeHidden(); + await span.waitFor({ state: 'hidden' }); + await browser.locator('[role=button]').waitFor({ state: 'visible' }); + }); + + test('isVisible during navigation should not throw', async ({ browser }) => { + for (let i = 0; i < 20; i++) { + await browser.goto(content(` + + `)).catch(() => {}); + expect(await browser.locator('div').isVisible()).toBe(false); + } + }); +}); diff --git a/apps/testbed/tests/locator-list.e2e.ts b/apps/testbed/tests/locator-list.e2e.ts new file mode 100644 index 0000000000..762f2b88fe --- /dev/null +++ b/apps/testbed/tests/locator-list.e2e.ts @@ -0,0 +1,19 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-list.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `div >> p` is the CSS `div p`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('locator list', { requires: ['browser'], tags: ['playwright'] }, () => { + test('locator.all should work', async ({ browser }) => { + await browser.goto(content(`

A

B

C

`)); + const texts = []; + for (const p of await browser.locator('div p').all()) + texts.push(await p.textContent()); + expect(texts).toEqual(['A', 'B', 'C']); + }); +}); diff --git a/apps/testbed/tests/locator-misc-2.e2e.ts b/apps/testbed/tests/locator-misc-2.e2e.ts new file mode 100644 index 0000000000..f84c53e078 --- /dev/null +++ b/apps/testbed/tests/locator-misc-2.e2e.ts @@ -0,0 +1,134 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-misc-2.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `scrollIntoViewIfNeeded` is + * `scrollIntoView`, an element's own `evaluate` a page `evaluate`. + * + * Not ported: + * - should select textarea: e2e has no selectText. + * - should type: deprecated `locator.type`; its replacement, pressSequentially, is ported. + * - should take screenshot: compares with Playwright's own golden image. + * - should combine visible with other selectors: `>> visible=true` selector chains. + * - should support filter(visible): e2e filter has no visible option. + * - should support visible(): e2e locators have no visible(). + * - Locator.locator() and FrameLocator.locator() should accept locator: e2e locators have no locator(locator). + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('locator misc 2', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should press @smoke', async ({ browser }) => { + await browser.goto(content(``)); + await browser.locator('input').press('h'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('h'); + }); + + test('should scroll into view', async ({ browser }) => { + await browser.goto('/offscreenbuttons.html'); + const overflow = '(id) => document.getElementById(id).getBoundingClientRect().right - window.innerWidth'; + for (let i = 0; i < 11; ++i) { + const before = await browser.evaluate(overflow, `btn${i}`); + expect(before).toBe(10 * i); + await browser.locator(`#btn${i}`).scrollIntoView(); + const after = await browser.evaluate(overflow, `btn${i}`); + expect(after <= 0).toBe(true); + await browser.evaluate('() => window.scrollTo(0, 0)'); + } + }); + + test('should scroll zero-sized element into view', async ({ browser }) => { + await browser.goto(content(` + +
+

SCROLL DOWN

+
+
+ + `)); + expect(await browser.locator('#lazyload').boundingBox()).toEqual({ x: 0, y: 2020, width: 1280, height: 0 }); + await browser.locator('#lazyload').scrollIntoView(); + await expect(browser.locator('#lazyload')).toHaveText('LAZY LOADED CONTENT'); + expect(await browser.locator('#lazyload').boundingBox()).toEqual({ x: 0, y: 720, width: 1280, height: 20 }); + }); + + test('should pressSequentially', async ({ browser }) => { + await browser.goto(content(``)); + await browser.locator('input').pressSequentially('hello'); + expect(await browser.evaluate("() => document.querySelector('input').value")).toBe('hello'); + }); + + test('should return bounding box', async ({ browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + const element = browser.locator('.box:nth-of-type(13)'); + const box = await element.boundingBox(); + expect(box).toEqual({ x: 100, y: 50, width: 50, height: 50 }); + }); + + test('should waitFor', async ({ browser }) => { + await browser.goto(content(`
`)); + const locator = browser.locator('span'); + const promise = locator.waitFor(); + await browser.evaluate("() => { document.querySelector('div').innerHTML = 'target'; }"); + await promise; + await expect(locator).toHaveText('target'); + }); + + test('should waitFor hidden', async ({ browser }) => { + await browser.goto(content(`
target
`)); + const locator = browser.locator('span'); + const promise = locator.waitFor({ state: 'hidden' }); + await browser.evaluate("() => { document.querySelector('div').innerHTML = ''; }"); + await promise; + }); + + test('locator.count should work with deleted Map in main world', { fail: '`browser.evaluate` and the in-page readers run in the main world, so a page that deletes `Map` breaks them; Playwright runs its own in a utility world' }, async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate('() => { window.Map = 1; }'); + await browser.locator('#searchResultTableDiv .x-grid3-row').count(); + await expect(browser.locator('#searchResultTableDiv .x-grid3-row')).toHaveCount(0); + }); + + test('should fill programmatically enabled textarea', async ({ browser }) => { + await browser.goto(content(` + +
+ +
+ + `)); + await browser.locator('button').click(); + await browser.locator('#text').fill('Hello'); + await expect(browser.locator('#text')).toHaveValue('Hello'); + }); + + test('press should throw on unknown keys', async ({ screen, browser }) => { + await browser.goto(content(``)); + const locator = screen.getByRole('textbox'); + for (const key of ['NotARealKey', 'ё', '😊']) { + const error = await locator.press(key).catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + expect((error as Error).message).toContain(key); + } + }); +}); diff --git a/apps/testbed/tests/locator-query.e2e.ts b/apps/testbed/tests/locator-query.e2e.ts new file mode 100644 index 0000000000..bc703735d6 --- /dev/null +++ b/apps/testbed/tests/locator-query.e2e.ts @@ -0,0 +1,186 @@ +/** + * Adapted from microsoft/playwright tests/page/locator-query.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `locator(css, { hasText, has })` is + * a locator `filter`, `div >> p` the CSS `div p`, a nested `.locator(css)` + * the matching semantic query scoped to the outer locator, `toHaveClass` the + * browser matcher, and `evaluate(e => e.outerHTML)` a text read. + * + * Not ported: + * - should throw on capture w/ nth(): Playwright `*css=` capture selector. + * - should throw on due to strictness 2: `locator.evaluate`. + * - should support locator.and: e2e locators have no and(). + * - should support locator.locator with and/or: e2e locators have no locator(locator) or and(). + * - should support locator.within: e2e locators have no within(). + * - should keep the capture when removing a common frame prefix: `*css=` captures and `contentFrame()`. + * - count() should not throw during navigation: custom selector engines. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +const sections = ` +
+

A

+

A

A

+

A

A

A

+
`; + +test.describe('locator query', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should respect first() and last() @smoke', async ({ browser }) => { + await browser.goto(content(sections)); + expect(await browser.locator('div p').count()).toBe(6); + expect(await browser.locator('div').first().getByText('A').count()).toBe(1); + expect(await browser.locator('div').last().getByText('A').count()).toBe(3); + }); + + test('should respect nth()', async ({ browser }) => { + await browser.goto(content(sections)); + expect(await browser.locator('div p').nth(0).count()).toBe(1); + expect(await browser.locator('div').nth(1).getByText('A').count()).toBe(2); + expect(await browser.locator('div').nth(2).getByText('A').count()).toBe(3); + }); + + test('should throw on due to strictness', async ({ browser }) => { + await browser.goto(content(`
A
B
`)); + const error = await browser.locator('div').isVisible().catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + }); + + test('should filter by text', async ({ browser }) => { + await browser.goto(content(`
Foobar
Bar
`)); + await expect(browser.locator('div').filter({ hasText: 'Foo' })).toHaveText('Foobar'); + }); + + test('should filter by text 2', async ({ browser }) => { + await browser.goto(content(`
foo hello world bar
`)); + await expect(browser.locator('div').filter({ hasText: 'hello world' })).toHaveText('foo hello world bar'); + }); + + test('should filter by regex', async ({ browser }) => { + await browser.goto(content(`
Foobar
Bar
`)); + await expect(browser.locator('div').filter({ hasText: /Foo.*/ })).toHaveText('Foobar'); + }); + + test('should filter by text with quotes', async ({ browser }) => { + await browser.goto(content(`
Hello "world"
Hello world
`)); + await expect(browser.locator('div').filter({ hasText: 'Hello "world"' })).toHaveText('Hello "world"'); + }); + + test('should filter by regex with quotes', async ({ browser }) => { + await browser.goto(content(`
Hello "world"
Hello world
`)); + await expect(browser.locator('div').filter({ hasText: /Hello "world"/ })).toHaveText('Hello "world"'); + }); + + test('should filter by regex with a single quote', async ({ screen, browser }) => { + await browser.goto(content(``)); + for (const pattern of [/let's/i, /let's/i, /'s/i, /'s/i, /let['abc]s/i, /let's let's/i, /let's let's/i]) { + await expect.soft(browser.locator('button').filter({ hasText: pattern }).getByText('hello')).toHaveText('hello'); + await expect.soft(screen.getByRole('button', { name: pattern }).getByText('hello')).toHaveText('hello'); + } + await expect.soft(browser.locator('button').filter({ hasText: /let\\'s/i })).not.toBeVisible(); + await expect.soft(screen.getByRole('button', { name: /let\\'s/i })).not.toBeVisible(); + + await browser.goto(content(``)); + await expect.soft(browser.locator('button').filter({ hasText: /let's/i })).not.toBeVisible(); + await expect.soft(screen.getByRole('button', { name: /let's/i })).not.toBeVisible(); + for (const pattern of [/let\\'s/i, /let\\'s/i, /let\\'s let\\'s/i, /let\\'s let\\'s/i]) { + await expect.soft(browser.locator('button').filter({ hasText: pattern }).getByText('hello')).toHaveText('hello'); + await expect.soft(screen.getByRole('button', { name: pattern }).getByText('hello')).toHaveText('hello'); + } + + await browser.goto(content(``)); + await expect.soft(browser.locator('button').filter({ hasText: /let's/iu })).toHaveText(`let's hello`); + await expect.soft(screen.getByRole('button', { name: /let's/iu })).toHaveText(`let's hello`); + }); + + test('should filter by regex and regexp flags', async ({ browser }) => { + await browser.goto(content(`
Hello "world"
Hello world
`)); + await expect(browser.locator('div').filter({ hasText: /hElLo "world"/i })).toHaveText('Hello "world"'); + }); + + test('should filter by case-insensitive regex in a child', async ({ browser }) => { + await browser.goto(content(`
Title Text
`)); + await expect(browser.locator('div').filter({ hasText: /^title text$/i })).toHaveText('Title Text'); + }); + + test('should filter by case-insensitive regex in multiple children', async ({ browser }) => { + await browser.goto(content(`
Title

Text

`)); + await expect(browser).toHaveClass(browser.locator('div').filter({ hasText: /^title text$/i }), 'test'); + }); + + test('should filter by regex with special symbols', async ({ browser }) => { + await browser.goto(content(`
First/"and"

Second\\

`)); + await expect(browser).toHaveClass(browser.locator('div').filter({ hasText: /^first\/".*"second\\$/si }), 'test'); + }); + + test('should support has:locator', async ({ screen, browser }) => { + await browser.goto(content(`
hello
world
`)); + await expect(browser.locator('div').filter({ has: screen.getByText('world', { exact: false }) })).toHaveCount(1); + expect(await browser.locator('div').filter({ has: screen.getByText('world', { exact: false }) }).textContent()).toBe('world'); + await expect(browser.locator('div').filter({ has: screen.getByText('hello') })).toHaveCount(1); + expect(await browser.locator('div').filter({ has: screen.getByText('hello') }).textContent()).toBe('hello'); + await expect(browser.locator('div').filter({ has: browser.locator('span') })).toHaveCount(2); + await expect(browser.locator('div').filter({ has: browser.locator('span').filter({ hasText: 'wor' }) })).toHaveCount(1); + expect(await browser.locator('div').filter({ has: browser.locator('span').filter({ hasText: 'wor' }) }).textContent()).toBe('world'); + await expect(browser.locator('div').filter({ has: browser.locator('span'), hasText: 'wor' })).toHaveCount(1); + }); + + test('should support locator.filter', async ({ browser }) => { + await browser.goto(content(`
hello
world
`)); + await expect(browser.locator('div').filter({ hasText: 'hello' })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasText: 'hello' }).filter({ hasText: 'hello' })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasText: 'hello' }).filter({ hasText: 'world' })).toHaveCount(0); + await expect(browser.locator('section').filter({ hasText: 'hello' }).filter({ hasText: 'world' })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasText: 'hello' }).getByText('hello')).toHaveCount(1); + await expect(browser.locator('div').filter({ has: browser.locator('span').filter({ hasText: 'world' }) })).toHaveCount(1); + await expect(browser.locator('div').filter({ has: browser.locator('span') })).toHaveCount(2); + await expect(browser.locator('div').filter({ has: browser.locator('span'), hasText: 'world' })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasNot: browser.locator('span').filter({ hasText: 'world' }) })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasNot: browser.locator('section') })).toHaveCount(2); + await expect(browser.locator('div').filter({ hasNot: browser.locator('span') })).toHaveCount(0); + await expect(browser.locator('div').filter({ hasNotText: 'hello' })).toHaveCount(1); + await expect(browser.locator('div').filter({ hasNotText: 'foo' })).toHaveCount(2); + }); + + test('should support locator.or', async ({ browser }) => { + await browser.goto(content(`
hello
world`)); + await expect(browser.locator('div').or(browser.locator('span'))).toHaveCount(2); + await expect(browser.locator('div').or(browser.locator('span'))).toHaveText(['hello', 'world']); + await expect(browser.locator('span').or(browser.locator('article')).or(browser.locator('div'))).toHaveText(['hello', 'world']); + await expect(browser.locator('article').or(browser.locator('something'))).toHaveCount(0); + await expect(browser.locator('article').or(browser.locator('div'))).toHaveText('hello'); + await expect(browser.locator('article').or(browser.locator('span'))).toHaveText('world'); + await expect(browser.locator('div').or(browser.locator('article'))).toHaveText('hello'); + await expect(browser.locator('span').or(browser.locator('article'))).toHaveText('world'); + }); + + test('should allow some, but not all nested frameLocators', async ({ browser }) => { + await browser.goto(content(`hello`)); + const frame = browser.frameLocator('iframe'); + await expect(frame.locator('span').or(frame.locator('article'))).toHaveText('world'); + await expect(frame.locator('article').or(frame.locator('span'))).toHaveText('world'); + const error = await expect(frame.locator('div').or(browser.frameLocator('#iframe').locator('span'))).toHaveText('world').catch((e: unknown) => e); + expect(error).toEqual(expect.any(Error)); + }); + + test('should enforce same frame for has/leftOf/rightOf/above/below/near', async ({ browser }) => { + await browser.goto('/frames/two-frames.html'); + const child = browser.frameLocator('iframe[name=uno]'); + let error: unknown; + try { + await browser.locator('div').filter({ has: child.locator('span') }).count(); + } catch (e) { + error = e; + } + expect(error).toEqual(expect.any(Error)); + }); + + test('alias methods coverage', async ({ screen, browser }) => { + await browser.goto(content(`
`)); + await expect(browser.locator('button')).toHaveCount(1); + await expect(browser.locator('div').getByRole('button')).toHaveCount(1); + await expect(screen.getByRole('button')).toHaveCount(1); + }); +}); diff --git a/apps/testbed/tests/network-idle.e2e.ts b/apps/testbed/tests/network-idle.e2e.ts new file mode 100644 index 0000000000..a1f036fb05 --- /dev/null +++ b/apps/testbed/tests/network-idle.e2e.ts @@ -0,0 +1,165 @@ +/** + * Adapted from microsoft/playwright tests/page/page-network-idle.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `page.setContent(html, { waitUntil })` is `browser.goto(content(html), { waitUntil })`, + * and a request the server holds is one a route holds. + */ + +/* + * Not ported: + * - should wait for networkidle in waitForNavigation: needs `page.waitForNavigation`. + * - should wait for networkidle when navigating iframe: needs `frame.goto`. + * - should wait for networkidle from the popup: needs `page.waitForEvent('popup')` and `popup.waitForLoadState`. + */ + +import { test, type Browser } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +/** A promise with its resolver, for a route handler the test holds open. */ +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +/** + * Playwright's `networkIdleTest`: holds `fetch-request-a.js` and `fetch-request-b.js` + * until the test answers them, and checks `action` settles only 500ms after the last. + */ +async function networkIdleTest(browser: Browser, action: () => Promise): Promise { + const held = (suffix: string) => { + const requested = deferred(); + const answer = deferred(); + return { suffix, requested, answer }; + }; + const a = held('/fetch-request-a.js'); + const b = held('/fetch-request-b.js'); + for (const request of [a, b]) { + await browser.route(`**${request.suffix}`, async (route) => { + request.requested.resolve(); + await request.answer.promise; + await route.fulfill({ status: 404, body: 'File not found' }); + }); + } + + const actionPromise = action(); + let actionFinished = false; + void actionPromise.then(() => (actionFinished = true)); + + await a.requested.promise; + expect(actionFinished).toBe(false); + + await browser.evaluate("() => window['fetchSecond']()"); + a.answer.resolve(); + + await b.requested.promise; + expect(actionFinished).toBe(false); + + let timerTriggered = false; + const timer = setTimeout(() => (timerTriggered = true), 500); + b.answer.resolve(); + + await actionPromise; + clearTimeout(timer); + expect(timerTriggered).toBe(true); +} + +test.describe('page network idle', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should navigate to empty page with networkidle', async ({ browser }) => { + const [response] = await Promise.all([ + browser.waitForResponse('**/empty.html'), + browser.goto(EMPTY_PAGE, { waitUntil: 'networkidle' }), + ]); + expect(response.status).toBe(200); + }); + + test('should wait for networkidle to succeed navigation', async ({ browser }) => { + await networkIdleTest(browser, () => browser.goto('/networkidle.html', { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle to succeed navigation with request from previous navigation', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content("")); + await networkIdleTest(browser, () => browser.goto('/networkidle.html', { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle in setContent', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await networkIdleTest(browser, () => browser.goto(content(""), { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle in setContent with request from previous navigation', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content("")); + await networkIdleTest(browser, () => browser.goto(content(""), { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle in setContent from the child frame', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await networkIdleTest(browser, () => browser.goto(content(""), { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle from the child frame', async ({ browser }) => { + await networkIdleTest(browser, () => browser.goto('/networkidle-frame.html', { waitUntil: 'networkidle' })); + }); + + test('should wait for networkidle when iframe attaches and detaches', async ({ browser }) => { + let done = false; + const promise = browser.goto(content(` + + + + `), { waitUntil: 'networkidle' }).then(() => (done = true)); + await new Promise((resolve) => setTimeout(resolve, 600)); + expect(done).toBe(false); + await browser.evaluate("() => { document.querySelector('iframe').remove(); }"); + await promise; + expect(done).toBe(true); + }); + + test('should work after repeated navigations in the same page', async ({ browser }) => { + let requestCount = 0; + await browser.route('**/empty.html', (route) => route.fulfill({ + contentType: 'text/html', + body: ` + `, + })); + await browser.route('**/sample', async (route) => { + requestCount++; + await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ content: 'sample' }) }); + }); + await browser.goto(EMPTY_PAGE, { waitUntil: 'networkidle' }); + expect(requestCount).toBe(1); + await browser.goto(EMPTY_PAGE, { waitUntil: 'networkidle' }); + expect(requestCount).toBe(2); + }); + + test('should not wait for an open EventSource connection', async ({ browser }) => { + const page = content(""); + const [response] = await Promise.all([ + browser.waitForResponse('**/content?**'), + browser.goto(page, { waitUntil: 'networkidle' }), + ]); + expect(response.status).toBe(200); + }); + + test('should not wait for an open EventSource connection in setContent', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(``), { waitUntil: 'networkidle' }); + await browser.evaluate("() => window['__sseOpened'].then(() => null)"); + }); +}); diff --git a/apps/testbed/tests/network.e2e.ts b/apps/testbed/tests/network.e2e.ts index 9e1f741ace..49a197527d 100644 --- a/apps/testbed/tests/network.e2e.ts +++ b/apps/testbed/tests/network.e2e.ts @@ -39,25 +39,6 @@ test.describe('network', { requires: ['browser'], tags: ['network'] }, () => { await expect(screen.getByText('Grace')).toBeVisible(); }); - test('stubs the API with route fulfillment', async ({ screen, browser }) => { - await browser.route('**/api/users', (route) => - route.fulfill({ json: [{ name: 'Stubbed' }] }), - ); - await screen.getByRole('button', 'Load users').tap(); - await expect(screen.getByRole('status', 'Network state')).toHaveText('loaded 1'); - await expect(screen.getByText('Stubbed')).toBeVisible(); - - await browser.unroute('**/api/users'); - await screen.getByRole('button', 'Load users').tap(); - await expect(screen.getByRole('status', 'Network state')).toHaveText('loaded 3'); - }); - - test('surfaces aborted requests as failures', async ({ screen, browser }) => { - await browser.route('**/api/users', (route) => route.abort()); - await screen.getByRole('button', 'Load users').tap(); - await expect(screen.getByRole('status', 'Network state')).toHaveText('failed'); - }); - test('evaluate inspects live page state', async ({ screen, browser }) => { await screen.getByRole('button', 'Load users').tap(); await expect(screen.getByRole('status', 'Network state')).toHaveText('loaded 3'); diff --git a/apps/testbed/tests/request-continue.e2e.ts b/apps/testbed/tests/request-continue.e2e.ts new file mode 100644 index 0000000000..9be4157606 --- /dev/null +++ b/apps/testbed/tests/request-continue.e2e.ts @@ -0,0 +1,426 @@ +/** + * Adapted from microsoft/playwright tests/page/page-request-continue.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: what the server received is what `/cors-echo` answers with. + */ + +/* + * Not ported: + * - should amend binary post data: `route.continue` takes a string `postData`. + * - should work with Cross-Origin-Opener-Policy: needs `page.on('request' | 'response' | 'requestfinished' | 'requestfailed')`. + * - redirected requests should report overridden headers: needs `route.fallback({ headers })` and `response.request()`. + * - postData should return empty string when overriding body with empty string: needs `page.waitForRequest`. + */ + +import { test, type Browser } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, CROSS, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +type Served = { method: string; headers: Record; body: string; url: string }; + +/** A promise with its resolver, for a route handler the test holds open. */ +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +/** The request the server received for the page now open, which `/cors-echo` printed as its text. */ +async function served(browser: Browser): Promise { + return JSON.parse(await browser.evaluate('document.body.textContent')) as Served; +} + +/** The request the server received for a page `fetch` to `url` with `init`, which `/cors-echo` answered with. */ +async function fetched(browser: Browser, url: string, init = '{}'): Promise { + return JSON.parse(await browser.evaluate(`(url) => fetch(url, ${init}).then((response) => response.text())`, url)) as Served; +} + +test.describe('page request continue', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should work', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue()); + await browser.goto(EMPTY_PAGE); + }); + + test('should amend HTTP headers', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue({ headers: { ...route.request.headers, FOO: 'bar' } })); + await browser.goto(EMPTY_PAGE); + const request = await fetched(browser, '/cors-echo'); + expect(request.headers['foo']).toBe('bar'); + }); + + test('should not allow to override unsafe HTTP headers', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue({ headers: { ...route.request.headers, host: 'bar', trailer: 'baz' } })); + await browser.goto('/cors-echo'); + const serverRequest = await served(browser); + expect(serverRequest.headers['trailer']).toBe(undefined); + expect(serverRequest.headers['host']).toBe(new URL(EMPTY_PAGE).host); + }); + + test('should delete header with undefined value', { fail: 'a header override takes strings only, so `undefined` cannot delete one' }, async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.route(`${PREFIX}/cors-echo`, (route) => route.continue({ + headers: { ...route.request.headers, foo: undefined } as unknown as Record, + })); + const serverRequest = await fetched(browser, `${PREFIX}/cors-echo`, "{ headers: { foo: 'a', bar: 'b' } }"); + expect(serverRequest.method).toBe('GET'); + expect(serverRequest.headers['foo']).toBeFalsy(); + expect(serverRequest.headers['bar']).toBe('b'); + }); + + test('should amend method', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue({ method: 'POST' })); + const request = await fetched(browser, '/cors-echo'); + expect(request.method).toBe('POST'); + }); + + test('should override request url', async ({ browser }) => { + await browser.route('**/foo', (route) => route.continue({ url: `${PREFIX}/global-var.html` })); + const [response] = await Promise.all([browser.waitForResponse(/\/(foo|global-var\.html)$/), browser.goto(`${PREFIX}/foo`)]); + expect(response.url).toBe(`${PREFIX}/global-var.html`); + expect(await browser.evaluate("() => window['globalVar']")).toBe(123); + }); + + test('should not allow changing protocol when overriding url', async ({ browser }) => { + const failed = deferred(); + await browser.route('**/*', async (route) => { + try { + await route.continue({ url: 'file:///tmp/foo' }); + failed.resolve(null); + } catch (caught) { + failed.resolve(caught as Error); + await route.abort(); + } + }); + const navigation = browser.goto(EMPTY_PAGE).catch(() => undefined); + const error = await failed.promise; + expect(error).toBeTruthy(); + expect(error!.message).toMatch(/scheme/); + await navigation; + }); + + test('should not throw if request was cancelled by the page', async ({ browser }) => { + const routed = deferred(); + const release = deferred(); + await browser.route('**/data.json', async (route) => { + routed.resolve(); + await release.promise; + await route.continue(); + }); + await browser.goto(EMPTY_PAGE); + await browser.evaluate(`(url) => { + globalThis.controller = new AbortController(); + globalThis.failure = fetch(url, { signal: globalThis.controller.signal }).then(() => 'loaded', (error) => error.name); + }`, `${PREFIX}/data.json`); + await routed.promise; + expect(await browser.evaluate('() => { globalThis.controller.abort(); return globalThis.failure; }')).toBe('AbortError'); + release.resolve(); + await browser.evaluate('() => new Promise((resolve) => setTimeout(resolve, 100))'); + }); + + test('should override method along with url', async ({ browser }) => { + await browser.route('**/foo', (route) => route.continue({ url: `${PREFIX}/cors-echo`, method: 'POST' })); + await browser.goto(`${PREFIX}/foo`); + expect((await served(browser)).method).toBe('POST'); + }); + + test('should amend method on main request', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue({ method: 'POST' })); + await browser.goto('/cors-echo'); + expect((await served(browser)).method).toBe('POST'); + }); + + test.describe('post data', () => { + test('should amend post data', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue({ postData: 'doggo' })); + const serverRequest = await fetched(browser, '/cors-echo', "{ method: 'POST', body: 'birdy' }"); + expect(serverRequest.body).toBe('doggo'); + }); + + test('should compute content-length from post data', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const data = 'a'.repeat(7500); + await browser.route('**/*', (route) => route.continue({ postData: data, headers: { ...route.request.headers, 'content-type': 'application/json' } })); + const serverRequest = await fetched(browser, '/cors-echo', "{ method: 'PATCH', body: 'birdy' }"); + expect(serverRequest.body).toBe(data); + expect(serverRequest.headers['content-length']).toBe(String(data.length)); + expect(serverRequest.headers['content-type']).toBe('application/json'); + }); + + test('should amend method and post data', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue({ method: 'POST', postData: 'doggo' })); + const serverRequest = await fetched(browser, '/cors-echo', "{ method: 'GET' }"); + expect(serverRequest.method).toBe('POST'); + expect(serverRequest.body).toBe('doggo'); + }); + + test('should amend utf8 post data', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue({ postData: 'пушкин' })); + const serverRequest = await fetched(browser, '/cors-echo', "{ method: 'POST', body: 'birdy' }"); + expect(serverRequest.method).toBe('POST'); + expect(serverRequest.body).toBe('пушкин'); + }); + + test('should amend longer post data', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue({ postData: 'doggo-is-longer-than-birdy' })); + const serverRequest = await fetched(browser, '/cors-echo', "{ method: 'POST', body: 'birdy' }"); + expect(serverRequest.method).toBe('POST'); + expect(serverRequest.body).toBe('doggo-is-longer-than-birdy'); + }); + + test('should use content-type from original request', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route(`${PREFIX}/cors-echo`, (route) => route.continue({ postData: '{"b":2}' })); + const request = await fetched(browser, `${PREFIX}/cors-echo`, `{ method: 'POST', body: '{"a":1}', headers: { 'content-type': 'application/json' } }`); + expect(request.headers['content-type']).toBe('application/json'); + expect(request.body).toBe('{"b":2}'); + }); + }); + + test('should not delete the origin header', async ({ browser }) => { + await browser.goto('/empty.html'); + let interceptedOrigin: string | undefined; + await browser.route(`${CROSS}/cors-echo`, async (route) => { + const headers = { ...route.request.headers }; + interceptedOrigin = headers['origin']; + delete headers['origin']; + await route.continue({ headers }); + }); + const serverRequest = await fetched(browser, `${CROSS}/cors-echo`); + expect(serverRequest.method).toBe('GET'); + expect(interceptedOrigin).toEqual(PREFIX); + expect(serverRequest.headers['origin']).toBe(PREFIX); + }); + + test('should continue preload link requests', async ({ browser }) => { + let intercepted = false; + await browser.route('**/one-style.css', async (route) => { + intercepted = true; + await route.continue({ headers: { ...route.request.headers, custom: 'value' } }); + }); + await browser.goto('/preload.html'); + await browser.evaluate('() => new Promise((resolve) => { const check = () => window.preloadedStyles ? resolve(true) : setTimeout(check, 20); check(); })'); + expect(intercepted).toBe(true); + // preload.html sets the flag before switching the link to a stylesheet, which applies a task later. + await expect.poll(() => browser.evaluate('() => window.getComputedStyle(document.body).backgroundColor')).toBe('rgb(255, 192, 203)'); + }); + + test('should respect set-cookie in redirect response', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/bounce?**', (route) => route.continue({ headers: { ...route.request.headers } })); + await browser.goto(`/bounce?cookie=${encodeURIComponent('foo=bar; max-age=36000')}&to=/cors-echo`); + expect((await served(browser)).headers['cookie']).toBe('foo=bar'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=bar'); + }); + + test('continue should not propagate cookie override to redirects', async ({ browser }) => { + await browser.goto('/set-cookie?cookie=foo=bar;'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=bar'); + await browser.route('**/redirect?**', (route) => route.continue({ headers: { ...route.request.headers, cookie: 'override' } })); + await browser.goto(`/redirect?to=${encodeURIComponent(`${PREFIX}/cors-echo`)}`); + expect((await served(browser)).headers['cookie']).toBe('foo=bar'); + }); + + test('continue should not override cookie', async ({ browser }) => { + await browser.goto('/set-cookie?cookie=foo=bar;'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=bar'); + await browser.route('**', (route) => route.continue({ headers: { ...route.request.headers, cookie: 'override', custom: 'value' } })); + await browser.goto('/cors-echo'); + const serverRequest = await served(browser); + expect(serverRequest.headers['cookie']).toBe('foo=bar'); + expect(serverRequest.headers['custom']).toBe('value'); + }); + + test('continue with headers should send fresh cookie from the browser cookie store', async ({ browser }) => { + await browser.goto('/set-cookie?cookie=foo=v1;'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=v1'); + await browser.route('**/cors-echo', async (route) => { + await browser.setCookies([{ name: 'foo', value: 'v2', url: PREFIX }]); + await route.continue({ headers: route.request.headers }); + }); + await browser.goto('/cors-echo'); + expect((await served(browser)).headers['cookie']).toBe('foo=v2'); + }); + + test('continue with headers should send fresh cookie after a redirect', async ({ browser }) => { + await browser.goto('/set-cookie?cookie=foo=v1;'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=v1'); + await browser.route('**/bounce?**', (route) => route.continue({ headers: route.request.headers })); + await browser.goto(`/bounce?cookie=${encodeURIComponent('foo=v2;')}&to=${encodeURIComponent(`${PREFIX}/cors-echo`)}`); + expect((await served(browser)).headers['cookie']).toBe('foo=v2'); + }); + + test('redirect after continue should be able to delete cookie', async ({ browser }) => { + await browser.goto('/set-cookie?cookie=foo=bar;'); + expect(await browser.evaluate('() => document.cookie')).toBe('foo=bar'); + await browser.route('**/redirect?**', (route) => route.continue({ headers: { ...route.request.headers } })); + await browser.goto(`/redirect?to=${encodeURIComponent(`/set-cookie?cookie=${encodeURIComponent('foo=bar; expires=Thu, 01 Jan 1970 00:00:00 GMT')}`)}`); + await browser.goto('/cors-echo'); + expect((await served(browser)).headers['cookie']).toBeFalsy(); + }); + + test('continue should propagate headers to redirects', async ({ browser }) => { + await browser.route('**/redirect?**', (route) => route.continue({ headers: { ...route.request.headers, custom: 'value' } })); + await browser.goto('/redirect?to=/cors-echo'); + expect((await served(browser)).headers['custom']).toBe('value'); + }); + + test('continue should drop content-length on redirects', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/redirect?**', (route) => route.continue({ headers: { ...route.request.headers, custom: 'value' } })); + const serverRequest = await fetched(browser, `${PREFIX}/redirect?to=/cors-echo`, "{ method: 'POST', body: 'foo' }"); + expect(serverRequest.method).toBe('GET'); + expect(serverRequest.headers['content-length']).toBeUndefined(); + expect(serverRequest.headers['content-type']).toBeUndefined(); + expect(serverRequest.headers['custom']).toBe('value'); + }); + + test('continue should delete headers on redirects', { fail: 'a header override takes strings only, so `undefined` cannot delete one' }, async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.route('**/redirect?**', (route) => route.continue({ + headers: { ...route.request.headers, foo: undefined } as unknown as Record, + })); + const serverRequest = await fetched(browser, `${PREFIX}/redirect?to=/cors-echo`, "{ headers: { foo: 'a' } }"); + expect(serverRequest.method).toBe('GET'); + expect(serverRequest.headers['foo']).toBeFalsy(); + }); + + test('propagate headers same origin redirect', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate("() => { document.cookie = 'a=b'; }"); + const serverRequest = await fetched( + browser, + `${PREFIX}/redirect?to=${encodeURIComponent('/cors-echo?preflight')}`, + "{ headers: { authorization: 'credentials', custom: 'foo' }, credentials: 'include' }", + ); + expect(serverRequest.headers['authorization']).toBe('credentials'); + expect(serverRequest.headers['cookie']).toBe('a=b'); + expect(serverRequest.headers['custom']).toBe('foo'); + }); + + test('propagate headers cross origin', async ({ browser }) => { + await browser.goto('/empty.html'); + const serverRequest = await fetched( + browser, + `${CROSS}/cors-echo?preflight`, + "{ headers: { authorization: 'credentials', custom: 'foo' }, credentials: 'include' }", + ); + expect(serverRequest.headers['authorization']).toBe('credentials'); + expect(serverRequest.headers['custom']).toBe('foo'); + }); + + test('propagate headers cross origin redirect', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate("() => { document.cookie = 'a=b'; }"); + const serverRequest = await fetched( + browser, + `${PREFIX}/bounce?status=301&to=${encodeURIComponent(`${CROSS}/cors-echo?preflight`)}`, + "{ headers: { authorization: 'credentials', custom: 'foo' }, credentials: 'include' }", + ); + expect(serverRequest.headers['authorization']).toBeFalsy(); + expect(serverRequest.headers['cookie']).toBeFalsy(); + expect(serverRequest.headers['custom']).toBe('foo'); + }); + + test('propagate headers cross origin redirect after interception', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate("() => { document.cookie = 'a=b'; }"); + await browser.route('**/bounce?**', (route) => route.continue({ headers: { ...route.request.headers, authorization: 'credentials', custom: 'foo' } })); + const serverRequest = await fetched( + browser, + `${PREFIX}/bounce?status=301&to=${encodeURIComponent(`${CROSS}/cors-echo?preflight`)}`, + "{ headers: { authorization: 'none' }, credentials: 'include' }", + ); + expect(serverRequest.headers['authorization']).toBe('credentials'); + expect(serverRequest.headers['cookie']).toBeFalsy(); + expect(serverRequest.headers['custom']).toBe('foo'); + }); + + test('continue should pass on 307 cross-origin redirect', async ({ browser }) => { + const final = `${PREFIX}${content('final

ok

')}`; + await browser.goto('/empty.html'); + await browser.goto(content(` +
+ +
`)); + await browser.route('**/*', (route) => route.continue()); + await Promise.all([ + browser.waitForURL(final), + browser.locator('input').tap(), + ]); + await expect(browser.locator('p')).toHaveText('ok'); + }); + + test('should intercept css variable with background url', async ({ browser }) => { + const intercepted = deferred(); + let interceptedRequests = 0; + await browser.route(`${PREFIX}/pptr.png`, async (route) => { + ++interceptedRequests; + intercepted.resolve(); + await route.continue(); + }); + await browser.goto(content(` + +
Yo!
`)); + expect(await browser.locator('div').textContent()).toBe('Yo!'); + await intercepted.promise; + await new Promise((resolve) => setTimeout(resolve, 1000)); + expect(interceptedRequests).toBe(1); + }); + + test('continue should not change multipart/form-data body', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const sendFormData = async (): Promise => { + const [status, body] = await browser.evaluate<[number, string]>(`async () => { + const newFile = new File(['file content'], 'file.txt'); + const formData = new FormData(); + formData.append('file', newFile); + const response = await fetch('/cors-echo', { method: 'POST', credentials: 'include', body: formData }); + return [response.status, (await response.json()).body]; + }`); + expect(status).toBe(200); + return body; + }; + const reqBefore = await sendFormData(); + await browser.route('**/*', (route) => route.continue()); + const reqAfter = await sendFormData(); + const fileContent = [ + 'Content-Disposition: form-data; name="file"; filename="file.txt"', + 'Content-Type: application/octet-stream', + '', + 'file content', + '------'].join('\r\n'); + expect(reqBefore).toContain(fileContent); + expect(reqAfter).toContain(fileContent); + }); + + test('should not forward Host header on cross-origin redirect', async ({ browser }) => { + await browser.route('**/*', async (route) => { + const headers = route.request.headers; + expect(headers).not.toHaveProperty('host'); + await route.continue({ headers }); + }); + const [response] = await Promise.all([ + browser.waitForResponse('**/cors-echo'), + browser.goto(`${PREFIX}/bounce?to=${encodeURIComponent(`${CROSS}/cors-echo`)}`), + ]); + expect(response.status).toBe(200); + expect((await served(browser)).headers['host']).toBe(new URL(CROSS).host); + }); +}); diff --git a/apps/testbed/tests/request-fallback.e2e.ts b/apps/testbed/tests/request-fallback.e2e.ts new file mode 100644 index 0000000000..0fab46b3b8 --- /dev/null +++ b/apps/testbed/tests/request-fallback.e2e.ts @@ -0,0 +1,93 @@ +/** + * Adapted from microsoft/playwright tests/page/page-request-fallback.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: a navigation's response is the one `browser.waitForResponse` sees. + */ + +/* + * Not ported: + * - should chain once: needs `route(..., { times })`. + * - should amend HTTP headers: needs `route.fallback({ headers })`. + * - should delete header with undefined value: needs `route.fallback({ headers })`. + * - should amend method: needs `route.fallback({ method })` and `page.waitForRequest`. + * - should override request url: needs `route.fallback({ url })`. + * - post data / should amend post data: needs `route.fallback({ postData })`. + * - post data / should amend binary post data: needs `route.fallback({ postData })` and `request.postDataBuffer()`. + * - post data / should amend json post data: needs `route.fallback({ postData })` and `request.postDataJSON()`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +test.describe('page request fallback', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should work', async ({ browser }) => { + await browser.route('**/*', (route) => route.fallback()); + await browser.goto(EMPTY_PAGE); + }); + + test('should fall back', async ({ browser }) => { + const intercepted: number[] = []; + for (const index of [1, 2, 3]) { + await browser.route('**/empty.html', async (route) => { + intercepted.push(index); + await route.fallback(); + }); + } + await browser.goto(EMPTY_PAGE); + expect(intercepted).toEqual([3, 2, 1]); + }); + + test('should fall back async', async ({ browser }) => { + const intercepted: number[] = []; + for (const index of [1, 2, 3]) { + await browser.route('**/empty.html', async (route) => { + intercepted.push(index); + await new Promise((resolve) => setTimeout(resolve, 100)); + await route.fallback(); + }); + } + await browser.goto(EMPTY_PAGE); + expect(intercepted).toEqual([3, 2, 1]); + }); + + test('should not chain fulfill', async ({ browser }) => { + let failed = false; + await browser.route('**/empty.html', async (route) => { + failed = true; + await route.continue(); + }); + await browser.route('**/empty.html', (route) => route.fulfill({ status: 200, body: 'fulfilled' })); + await browser.route('**/empty.html', (route) => route.fallback()); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(EMPTY_PAGE)]); + expect(await response.text()).toEqual('fulfilled'); + expect(failed).toBeFalsy(); + }); + + test('should not chain abort', async ({ browser }) => { + let failed = false; + await browser.route('**/empty.html', async (route) => { + failed = true; + await route.continue(); + }); + await browser.route('**/empty.html', (route) => route.abort()); + await browser.route('**/empty.html', (route) => route.fallback()); + const e = await browser.goto(EMPTY_PAGE).catch((caught: Error) => caught); + expect(e).toBeTruthy(); + expect(failed).toBeFalsy(); + }); + + test('should fall back after exception', async ({ browser }) => { + await browser.route('**/empty.html', (route) => route.continue()); + await browser.route('**/empty.html', async (route) => { + try { + await route.fulfill({ response: {} } as never); + } catch { + await route.fallback(); + } + }); + await browser.goto(EMPTY_PAGE); + }); +}); diff --git a/apps/testbed/tests/request-fulfill.e2e.ts b/apps/testbed/tests/request-fulfill.e2e.ts new file mode 100644 index 0000000000..21ffeffa76 --- /dev/null +++ b/apps/testbed/tests/request-fulfill.e2e.ts @@ -0,0 +1,239 @@ +/** + * Adapted from microsoft/playwright tests/page/page-request-fulfill.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: a navigation's response is the one `browser.waitForResponse` sees. + */ + +/* + * Not ported: + * - should work with buffer as body: `route.fulfill` takes a string body. + * - should allow mocking binary responses: needs a Buffer body and `toMatchSnapshot`. + * - should fulfill with global fetch result: needs `playwright.request` and `fulfill({ response })`. + * - should fulfill with fetch result: needs `page.request` and `fulfill({ response })`. + * - should fulfill with fetch result and overrides: needs `page.request` and `fulfill({ response })`. + * - headerValue should return set-cookie from intercepted response: Playwright expects it to fail on Chromium. + * - should fulfill with har response: HAR. + * - should fulfill with gzip and readback: needs a gzip server and `fulfill({ response })`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { asset, content, CROSS, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +/** A promise with its resolver, for a route handler the test holds open. */ +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +/** Polls the page until `expression` is truthy, Playwright's `page.waitForFunction`. */ +const waitForFunction = (expression: string): string => + `() => new Promise((resolve) => { const check = () => (${expression}) ? resolve(true) : setTimeout(check, 20); check(); })`; + +test.describe('page request fulfill', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should work', async ({ browser }) => { + await browser.route('**/*', (route) => route.fulfill({ status: 201, headers: { foo: 'bar' }, contentType: 'text/html', body: 'Yo, page!' })); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(EMPTY_PAGE)]); + expect(response.status).toBe(201); + expect(response.headers['foo']).toBe('bar'); + expect(await browser.evaluate('() => document.body.textContent')).toBe('Yo, page!'); + }); + + test('should work with status code 422', async ({ browser }) => { + await browser.route('**/*', (route) => route.fulfill({ status: 422, body: 'Yo, page!' })); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(EMPTY_PAGE)]); + expect(response.status).toBe(422); + expect(await browser.evaluate('() => document.body.textContent')).toBe('Yo, page!'); + }); + + test('should fulfill with unuassigned status codes', async ({ browser }) => { + const fulfilled = deferred(); + await browser.route('**/data.json', async (route) => { + fulfilled.resolve(await route.fulfill({ status: 430, body: 'Yo, page!' }).then(() => undefined, (caught: Error) => caught)); + }); + await browser.goto(EMPTY_PAGE); + const response = await browser.evaluate<{ status: number; statusText: string }, string>( + 'async (url) => { const { status, statusText } = await fetch(url); return { status, statusText }; }', + `${PREFIX}/data.json`, + ); + const error = await fulfilled.promise; + expect(error).toBe(undefined); + expect(response.status).toBe(430); + expect(response.statusText).toBe('Unknown'); + }); + + test('should not throw if request was cancelled by the page', async ({ browser }) => { + const routed = deferred(); + const release = deferred(); + await browser.route('**/data.json', async (route) => { + routed.resolve(); + await release.promise; + await route.fulfill({ status: 200 }); + }); + await browser.goto(EMPTY_PAGE); + await browser.evaluate(`(url) => { + globalThis.controller = new AbortController(); + globalThis.failure = fetch(url, { signal: globalThis.controller.signal }).then(() => 'loaded', (error) => error.name); + }`, `${PREFIX}/data.json`); + await routed.promise; + expect(await browser.evaluate('() => { globalThis.controller.abort(); return globalThis.failure; }')).toBe('AbortError'); + release.resolve(); + await browser.evaluate('() => new Promise((resolve) => setTimeout(resolve, 100))'); + }); + + test('should allow mocking svg with charset', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.fulfill({ + contentType: 'image/svg+xml ; charset=utf-8', + body: '', + })); + const size = await browser.evaluate(`(PREFIX) => { + const img = document.createElement('img'); + img.src = PREFIX + '/does-not-exist.svg'; + document.body.appendChild(img); + return new Promise((resolve, reject) => { img.onload = () => resolve([img.naturalWidth, img.naturalHeight]); img.onerror = reject; }); + }`, PREFIX); + expect(size).toEqual([50, 50]); + }); + + test('should work with file path', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.fulfill({ contentType: 'shouldBeIgnored', path: asset('pptr.png') })); + const size = await browser.evaluate(`(PREFIX) => { + const img = document.createElement('img'); + img.src = PREFIX + '/does-not-exist.png'; + document.body.appendChild(img); + return new Promise((resolve) => { img.onload = () => resolve([img.naturalWidth, img.naturalHeight]); }); + }`, PREFIX); + expect(size).toEqual([69, 100]); + }); + + test('should stringify intercepted request response headers', async ({ browser }) => { + await browser.route('**/*', (route) => route.fulfill({ status: 200, headers: { foo: 'true' }, body: 'Yo, page!' })); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(EMPTY_PAGE)]); + expect(response.status).toBe(200); + expect(response.headers['foo']).toBe('true'); + expect(await browser.evaluate('() => document.body.textContent')).toBe('Yo, page!'); + }); + + test('should not modify the headers sent to the server', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.route(`${PREFIX}/unused`, (route) => route.continue()); + const fetchServed = 'async (url) => { const data = await fetch(url); return data.text(); }'; + const served = await browser.evaluate(fetchServed, `${CROSS}/cors-echo`); + const before = JSON.parse(served) as { method: string; headers: Record }; + expect(before.method).toBe('GET'); + + await browser.route(`${CROSS}/cors-echo`, (route) => route.continue({ headers: { ...route.request.headers } })); + const servedAfterRoute = await browser.evaluate(fetchServed, `${CROSS}/cors-echo`); + const after = JSON.parse(servedAfterRoute) as { method: string; headers: Record }; + expect(after.method).toBe('GET'); + expect(after.headers).toEqual(before.headers); + }); + + test('should include the origin header', async ({ browser }) => { + await browser.goto('/empty.html'); + let origin: string | undefined; + await browser.route(`${CROSS}/something`, async (route) => { + origin = route.request.headers['origin']; + await route.fulfill({ headers: { 'Access-Control-Allow-Origin': '*' }, contentType: 'text/plain', body: 'done' }); + }); + const text = await browser.evaluate('async (url) => { const data = await fetch(url); return data.text(); }', `${CROSS}/something`); + expect(text).toBe('done'); + expect(origin).toEqual(PREFIX); + }); + + test('should fetch original request and fulfill', async ({ browser }) => { + await browser.route('**/*', async (route) => { + const response = await route.fetch(); + await route.fulfill({ status: response.status, headers: { ...response.headers }, body: await response.text() }); + }); + const [response] = await Promise.all([browser.waitForResponse('**/title.html'), browser.goto('/title.html')]); + expect(response.status).toBe(200); + expect(await browser.title()).toEqual('Woof-Woof'); + }); + + test('should fulfill with multiple set-cookie', { skip: '`route.fulfill` refuses a header value with a newline, so the request is aborted and the navigation fails as an engine failure, which `fail` does not cover' }, async ({ browser }) => { + const cookies = ['a=b', 'c=d']; + await browser.route('**/multiple-set-cookie.html', (route) => route.fulfill({ + status: 200, + headers: { 'X-Header-1': 'v1', 'Set-Cookie': cookies.join('\n'), 'X-Header-2': 'v2' }, + body: '', + })); + const [response] = await Promise.all([ + browser.waitForResponse('**/multiple-set-cookie.html'), + browser.goto('/multiple-set-cookie.html'), + ]); + const cookie = await browser.evaluate('() => document.cookie'); + expect(cookie.split(';').map((s) => s.trim()).toSorted()).toEqual(cookies); + expect(response.headers['x-header-1']).toBe('v1'); + expect(response.headers['x-header-2']).toBe('v2'); + }); + + test('should fulfill with fetch response that has multiple set-cookie', { skip: '`route.fulfill` refuses a header value with a newline, so the request is aborted and the navigation fails as an engine failure, which `fail` does not cover' }, async ({ browser }) => { + await browser.route('**/respond?*', async (route) => { + const response = await route.fetch(); + await route.fulfill({ status: response.status, headers: { ...response.headers }, body: await response.text() }); + }); + const headers = JSON.stringify({ 'set-cookie': ['a=b', 'c=d'], 'content-type': 'text/html' }); + await browser.goto(`/respond?headers=${encodeURIComponent(headers)}`); + const cookie = await browser.evaluate('() => document.cookie'); + expect(cookie.split(';').map((s) => s.trim()).toSorted()).toEqual(['a=b', 'c=d']); + }); + + test('should fulfill preload link requests', async ({ browser }) => { + let intercepted = false; + await browser.route('**/one-style.css', async (route) => { + intercepted = true; + await route.fulfill({ + status: 200, + headers: { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-cache, no-store', custom: 'value' }, + body: 'body { background-color: green; }', + }); + }); + const [response] = await Promise.all([browser.waitForResponse('**/one-style.css'), browser.goto('/preload.html')]); + expect(response.headers['custom']).toBe('value'); + await browser.evaluate(waitForFunction('window.preloadedStyles')); + expect(intercepted).toBe(true); + // preload.html sets the flag before switching the link to a stylesheet, which applies a task later. + await expect.poll(() => browser.evaluate('() => window.getComputedStyle(document.body).backgroundColor')).toBe('rgb(0, 128, 0)'); + }); + + test('should fulfill json', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/data.json', (route) => route.fulfill({ status: 201, headers: { foo: 'bar' }, json: { bar: 'baz' } })); + const [response, body] = await Promise.all([ + browser.waitForResponse('**/*'), + browser.evaluate("() => fetch('./data.json').then((r) => r.text())"), + ]); + expect(response.status).toBe(201); + expect(response.headers['content-type']).toBe('application/json'); + expect(body).toBe(JSON.stringify({ bar: 'baz' })); + }); + + test('should not go to the network for fulfilled requests body', async ({ browser }) => { + const key = `fulfilled-${Date.now()}-${Math.random()}`; + await browser.route(`**/count?key=${key}`, (route) => route.fulfill({ status: 404, contentType: 'text/plain', body: 'Not Found! (mocked)' })); + const [response] = await Promise.all([ + browser.waitForResponse(`**/count?key=${key}`), + browser.goto(content(`
hello, world!
`)), + ]); + expect(await response.text()).toBe('Not Found! (mocked)'); + await browser.unrouteAll(); + const serverHits = await browser.evaluate("(key) => fetch('/count?key=' + key).then((r) => r.text())", key); + expect(serverHits).toBe('11'); + }); + + test('should return body for fulfilled responses', async ({ browser }) => { + for (const status of [100, 200, 404, 500]) { + const bodyOverride = `Custom body ${status}`; + await browser.route('**/one-style.css', (route) => route.fulfill({ status, contentType: 'text/plain', body: bodyOverride })); + const [response] = await Promise.all([browser.waitForResponse('**/one-style.css'), browser.goto('/one-style.html')]); + expect(await response.text()).toBe(bodyOverride); + await browser.unrouteAll(); + } + }); +}); diff --git a/apps/testbed/tests/route.e2e.ts b/apps/testbed/tests/route.e2e.ts new file mode 100644 index 0000000000..e65bee82e7 --- /dev/null +++ b/apps/testbed/tests/route.e2e.ts @@ -0,0 +1,641 @@ +/** + * Adapted from microsoft/playwright tests/page/page-route.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: a navigation's response is the one `browser.waitForResponse` sees. + */ + +/* + * Not ported: + * - should navigate to dataURL and not fire dataURL requests: `goto` refuses `data:` URLs on purpose. + * - should show custom HTTP headers: needs `page.setExtraHTTPHeaders`. + * - should work with custom referer headers: needs `page.setExtraHTTPHeaders`. + * - should send referer: needs `page.setExtraHTTPHeaders`. + * - should be abortable with custom error codes: needs `route.abort(errorCode)` and `requestfailed`. + * - should chain fallback w/ dynamic URL: needs `route.fallback({ url })`. + * - should not fulfill with redirect status: WebKit only. + * - should support the times parameter with route matching: needs `route(..., { times })`. + * - should work if handler with times parameter was removed from another handler: needs `route(..., { times })`. + * - should support async handler w/ times: needs `route(..., { times })`. + * - route abort with times: 1 should not affect second sequential fetch: needs `route(..., { times })` and `route.abort(errorCode)`. + * - should contain sec-fetch headers in route: needs `request.allHeaders()`, and fails on Chromium by design. + * - should contain raw response header: needs `request.response()`. + * - should contain raw response header after fulfill: needs `request.response()`. + * - should be able to intercept every navigation to a page controlled by service worker: service workers. + * - should respect URLPattern ignoreCase: `route` takes a glob or RegExp, not a URLPattern. + */ + +import { test, type WebRoute } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, CROSS, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +/** A promise with its resolver, for a route handler the test holds open. */ +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} + +test.describe('page route', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should intercept @smoke', async ({ browser }) => { + let intercepted = false; + await browser.route('**/empty.html', async (route) => { + expect(route.request.url).toContain('empty.html'); + expect(route.request.headers['user-agent']).toBeTruthy(); + expect(route.request.method).toBe('GET'); + expect(route.request.postData).toBe(undefined); + await route.continue(); + intercepted = true; + }); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(EMPTY_PAGE)]); + expect(response.status).toBe(200); + expect(intercepted).toBe(true); + }); + + test('should unroute', async ({ browser }) => { + let intercepted: number[] = []; + await browser.route('**/*', async (route) => { + intercepted.push(1); + await route.fallback(); + }); + await browser.route('**/empty.html', async (route) => { + intercepted.push(2); + await route.fallback(); + }); + await browser.route('**/empty.html', async (route) => { + intercepted.push(3); + await route.fallback(); + }); + await browser.route(/empty.html/, async (route) => { + intercepted.push(4); + await route.fallback(); + }); + await browser.goto(EMPTY_PAGE); + expect(intercepted).toEqual([4, 3, 2, 1]); + + intercepted = []; + await browser.unroute(/empty.html/); + await browser.goto(EMPTY_PAGE); + expect(intercepted).toEqual([3, 2, 1]); + + intercepted = []; + await browser.unroute('**/empty.html'); + await browser.goto(EMPTY_PAGE); + expect(intercepted).toEqual([1]); + }); + + test('should not support ? in glob pattern', { fail: '`?` in a route glob matches one character, where Playwright reads it literally' }, async ({ browser }) => { + await browser.route(/\/index/, async (route) => { + const { pathname, search } = new URL(route.request.url); + const body = { '/index': 'index-no-hello', '/index123hello': 'index123hello', '/index1hello': 'index1hello' }[pathname] ?? `${pathname.slice(1)}${search}`; + await route.fulfill({ body, contentType: 'text/html' }); + }); + await browser.route('**/index?hello', (route) => route.fulfill({ body: 'intercepted any character' })); + await browser.route('**/index\\?hello', (route) => route.fulfill({ body: 'intercepted question mark' })); + + await browser.goto(`${PREFIX}/index?hello`); + expect(await browser.evaluate('document.documentElement.outerHTML')).toContain('intercepted question mark'); + + await browser.goto(`${PREFIX}/index`); + expect(await browser.evaluate('document.documentElement.outerHTML')).toContain('index-no-hello'); + + await browser.goto(`${PREFIX}/index1hello`); + expect(await browser.evaluate('document.documentElement.outerHTML')).toContain('index1hello'); + + await browser.goto(`${PREFIX}/index123hello`); + expect(await browser.evaluate('document.documentElement.outerHTML')).toContain('index123hello'); + }); + + test('should work when POST is redirected with 302', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', (route) => route.continue()); + await browser.goto(content(` +
+ +
+ `)); + await Promise.all([ + browser.evaluate("() => { document.querySelector('form').submit(); }"), + browser.waitForURL('/empty.html'), + ]); + }); + + test('should work when header manipulation headers with redirect', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue({ headers: { ...route.request.headers, foo: 'bar' } })); + await browser.goto('/redirect?to=/empty.html'); + }); + + test('should be able to remove headers', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/*', async (route) => { + const headers = { ...route.request.headers }; + delete headers['foo']; + await route.continue({ headers }); + }); + const served = await browser.evaluate<{ headers: Record }, string>( + "(url) => fetch(url, { headers: { foo: 'bar' } }).then((response) => response.json())", + `${PREFIX}/cors-echo`, + ); + expect(served.headers['foo']).toBe(undefined); + }); + + test('should contain referer header', async ({ browser }) => { + const requests: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + requests.push(route.request); + await route.continue(); + }); + await browser.goto('/one-style.html'); + expect(requests[1]!.url).toContain('/one-style.css'); + expect(requests[1]!.headers['referer']).toContain('/one-style.html'); + }); + + test('should properly return navigation response when URL has cookies', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.setCookies([{ url: EMPTY_PAGE, name: 'foo', value: 'bar' }]); + await browser.route('**/*', (route) => route.continue()); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.reload()]); + expect(response.status).toBe(200); + }); + + test('should not override cookie header', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.evaluate("() => { document.cookie = 'original=value'; }"); + let cookieValueInRoute: string | undefined; + await browser.route('**', async (route) => { + const headers = { ...route.request.headers }; + cookieValueInRoute = headers['cookie']; + headers['cookie'] = 'overridden=value'; + await route.continue({ headers }); + }); + await browser.goto('/cors-echo'); + const served = JSON.parse(await browser.evaluate('document.body.textContent')) as { headers: Record }; + expect(cookieValueInRoute).toBe('original=value'); + expect(served.headers['cookie']).toBe('original=value'); + }); + + test('should work with redirect inside sync XHR', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + let continued = false; + await browser.route('**/*', async (route) => { + await route.continue(); + continued = true; + }); + const status = await browser.evaluate(`() => { + const request = new XMLHttpRequest(); + request.open('GET', '/redirect?to=/pptr.png', false); + request.send(null); + return request.status; + }`); + expect(status).toBe(200); + expect(continued).toBe(true); + }); + + test('should pause intercepted XHR until continue', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const routed = deferred(); + const release = deferred(); + await browser.route('**/global-var.html', async (route) => { + routed.resolve(); + await release.promise; + await route.continue(); + }); + let xhrFinished = false; + const statusPromise = browser.evaluate(`() => { + const request = new XMLHttpRequest(); + request.open('GET', '/global-var.html', false); + request.send(null); + return request.status; + }`).then((status) => { + xhrFinished = true; + return status; + }); + await routed.promise; + await new Promise((resolve) => setTimeout(resolve, 500)); + expect(xhrFinished).toBe(false); + release.resolve(); + expect(await statusPromise).toBe(200); + }); + + test('should pause intercepted fetch request until continue', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const routed = deferred(); + const release = deferred(); + await browser.route('**/global-var.html', async (route) => { + routed.resolve(); + await release.promise; + await route.continue(); + }); + let fetchFinished = false; + const statusPromise = browser.evaluate("async () => (await fetch('/global-var.html')).status").then((status) => { + fetchFinished = true; + return status; + }); + await routed.promise; + await new Promise((resolve) => setTimeout(resolve, 500)); + expect(fetchFinished).toBe(false); + release.resolve(); + expect(await statusPromise).toBe(200); + }); + + test('should be abortable', async ({ browser }) => { + await browser.route(/\.css$/, (route) => route.abort()); + const [response] = await Promise.all([browser.waitForResponse('**/one-style.html'), browser.goto('/one-style.html')]); + expect(response.status).toBe(200); + expect(await browser.evaluate('getComputedStyle(document.body).backgroundColor')).not.toBe('rgb(255, 192, 203)'); + }); + + test('should not throw if request was cancelled by the page', async ({ browser }) => { + const routed = deferred(); + const release = deferred(); + await browser.route('**/data.json', async (route) => { + routed.resolve(); + await release.promise; + await route.abort(); + }); + await browser.goto(EMPTY_PAGE); + await browser.evaluate(`(url) => { + globalThis.controller = new AbortController(); + globalThis.failure = fetch(url, { signal: globalThis.controller.signal }).then(() => 'loaded', (error) => error.name); + }`, `${PREFIX}/data.json`); + await routed.promise; + expect(await browser.evaluate('() => { globalThis.controller.abort(); return globalThis.failure; }')).toBe('AbortError'); + release.resolve(); + await browser.evaluate('() => new Promise((resolve) => setTimeout(resolve, 100))'); + }); + + test('should fail navigation when aborting main resource', async ({ browser }) => { + await browser.route('**/*', (route) => route.abort()); + const error = await browser.goto(EMPTY_PAGE).catch((caught: Error) => caught); + expect(error).toBeTruthy(); + expect((error as Error).message).toContain('net::ERR_FAILED'); + }); + + test('should not work with redirects', async ({ browser }) => { + const intercepted: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + await route.continue(); + intercepted.push(route.request); + }); + const chain = ['/non-existing-page.html', '/non-existing-page-2.html', '/non-existing-page-3.html', '/non-existing-page-4.html']; + const start = chain.reduceRight((to, from) => `/redirect?from=${from}&to=${encodeURIComponent(to)}`, '/empty.html'); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(start)]); + expect(response.status).toBe(200); + expect(response.url).toContain('empty.html'); + + expect(intercepted.length).toBe(1); + expect(intercepted[0]!.url).toContain('/non-existing-page.html'); + }); + + test('should work with redirects for subresources', async ({ browser }) => { + const intercepted: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + await route.continue(); + intercepted.push(route.request); + }); + const chain = ['/one-style.css', '/two-style.css', '/three-style.css']; + const stylesheet = chain.reduceRight((to, from) => `/redirect?from=${from}&to=${encodeURIComponent(to)}`, '/one-style.css'); + const page = content(`
hello, world!
`); + const [response] = await Promise.all([browser.waitForResponse('**/content?**'), browser.goto(page)]); + expect(response.status).toBe(200); + expect(response.url).toContain('/content?'); + + expect(intercepted.length).toBe(2); + expect(intercepted[0]!.url).toContain('/content?'); + expect(intercepted[1]!.url).toContain('/one-style.css'); + }); + + test('should work with equal requests', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const key = `equal-${Date.now()}-${Math.random()}`; + let spinner = false; + await browser.route('**/*', async (route) => { + await (spinner ? route.abort() : route.continue()); + spinner = !spinner; + }); + const results = []; + for (let i = 0; i < 3; i++) { + results.push(await browser.evaluate("(key) => fetch('/count?key=' + key).then((response) => response.text()).catch(() => 'FAILED')", key)); + } + expect(results).toEqual(['11', 'FAILED', '22']); + }); + + test('should be able to fetch dataURL and not fire dataURL requests', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const requests: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + requests.push(route.request); + await route.continue(); + }); + const text = await browser.evaluate('(url) => fetch(url).then((response) => response.text())', 'data:text/html,
yo
'); + expect(text).toBe('
yo
'); + expect(requests.length).toBe(0); + }); + + test('should navigate to URL with hash and and fire requests without hash', async ({ browser }) => { + const requests: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + requests.push(route.request); + await route.continue(); + }); + const [response] = await Promise.all([browser.waitForResponse('**/empty.html'), browser.goto(`${EMPTY_PAGE}#hash`)]); + expect(response.status).toBe(200); + expect(response.url).toBe(EMPTY_PAGE); + expect(requests.length).toBe(1); + expect(requests[0]!.url).toBe(EMPTY_PAGE); + }); + + test('should work with encoded server', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue()); + const [response] = await Promise.all([browser.waitForResponse(/nonexisting/), browser.goto(`${PREFIX}/some nonexisting page`)]); + expect(response.status).toBe(404); + }); + + test('should work with badly encoded server', async ({ browser }) => { + await browser.route('**/*', (route) => route.continue()); + const [response] = await Promise.all([browser.waitForResponse(/rnd=/), browser.goto(`${PREFIX}/status?rnd=%911`)]); + expect(response.status).toBe(200); + }); + + test('should work with encoded server - 2', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const requests: WebRoute['request'][] = []; + await browser.route('**/*', async (route) => { + await route.continue(); + if (!route.request.url.includes('/content?')) requests.push(route.request); + }); + const [response] = await Promise.all([ + browser.waitForResponse(/\/fonts\?/), + browser.goto(content(``)), + ]); + expect(requests.length).toBe(1); + expect(response.status).toBe(404); + }); + + test('should not throw "Invalid Interception Id" if the request was cancelled', async ({ browser }) => { + await browser.goto(content('')); + const routed = deferred(); + const release = deferred(); + await browser.route('**/*', async (route) => { + routed.resolve(); + await release.promise; + await route.continue(); + }); + await browser.evaluate("(url) => { document.querySelector('iframe').src = url; }", EMPTY_PAGE); + await routed.promise; + await browser.evaluate("() => document.querySelector('iframe').remove()"); + release.resolve(); + await browser.evaluate('() => new Promise((resolve) => setTimeout(resolve, 100))'); + }); + + test('should intercept main resource during cross-process navigation', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + let intercepted = false; + await browser.route(`${CROSS}/empty.html`, async (route) => { + intercepted = true; + await route.continue(); + }); + const [response] = await Promise.all([browser.waitForResponse(`${CROSS}/empty.html`), browser.goto(`${CROSS}/empty.html`)]); + expect(response.status).toBe(200); + expect(intercepted).toBe(true); + }); + + test('should fulfill with redirect status', async ({ browser }) => { + await browser.goto('/title.html'); + await browser.route('**/*', async (route) => { + if (route.request.url !== `${PREFIX}/redirect_this`) return route.continue(); + await route.fulfill({ status: 301, headers: { location: '/status?body=foo' } }); + }); + const text = await browser.evaluate('async (url) => (await fetch(url)).text()', `${PREFIX}/redirect_this`); + expect(text).toBe('foo'); + }); + + test('should support cors with GET', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars*', async (route) => { + const headers = { 'access-control-allow-origin': route.request.url.endsWith('allow') ? '*' : 'none' }; + await route.fulfill({ contentType: 'application/json', headers, status: 200, body: JSON.stringify(['electric', 'gas']) }); + }); + const resp = await browser.evaluate("async () => (await fetch('https://example.com/cars?allow', { mode: 'cors' })).json()"); + expect(resp).toEqual(['electric', 'gas']); + const error = await browser.evaluate("async () => (await fetch('https://example.com/cars?reject', { mode: 'cors' })).json()").catch((caught: Error) => caught); + expect((error as Error).message).toContain('Failed'); + }); + + test('should add Access-Control-Allow-Origin by default when fulfill', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars', (route) => route.fulfill({ contentType: 'application/json', status: 200, body: JSON.stringify(['electric', 'gas']) })); + const [result, response] = await Promise.all([ + browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + }); + return response.json(); + }`), + browser.waitForResponse('https://example.com/cars'), + ]); + expect(result).toEqual(['electric', 'gas']); + expect(response.headers['access-control-allow-origin']).toBe(PREFIX); + }); + + test('should allow null origin for about:blank', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto('about:blank'); + await browser.route('**/something', (route) => route.fulfill({ contentType: 'text/plain', status: 200, body: 'done' })); + const [response, text] = await Promise.all([ + browser.waitForResponse(`${CROSS}/something`), + browser.evaluate(`async (url) => { + const data = await fetch(url, { method: 'GET', headers: { 'X-PINGOTHER': 'pingpong' } }); + return data.text(); + }`, `${CROSS}/something`), + ]); + expect(text).toBe('done'); + expect(response.headers['access-control-allow-origin']).toBe('null'); + }); + + test('should respect cors overrides', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/something', (route) => route.fulfill({ + contentType: 'text/plain', + status: 200, + headers: { 'Access-Control-Allow-Origin': 'http://non-existent' }, + body: 'done', + })); + const error = await browser.evaluate(`async (url) => { + const data = await fetch(url, { method: 'GET', headers: { 'X-PINGOTHER': 'pingpong' } }); + return data.text(); + }`, `${CROSS}/something`).catch((caught: Error) => caught); + expect((error as Error).message).toContain('Failed to fetch'); + }); + + test('should not auto-intercept non-preflight OPTIONS without network interception', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const key = `options-${Date.now()}-${Math.random()}`; + const [text1, text2] = await browser.evaluate(`async (url) => { + const response1 = await fetch(url, { method: 'OPTIONS' }); + const text1 = await response1.text(); + const response2 = await fetch(url, { method: 'GET' }); + const text2 = await response2.text(); + return [text1, text2]; + }`, `${CROSS}/options?key=${key}`); + expect(text1).toBe('Hello'); + expect(text2).toBe('World'); + expect(await browser.evaluate('(key) => fetch(`/options-log?key=${key}`).then((response) => response.json())', key)).toEqual(['OPTIONS:/options', 'OPTIONS:/options', 'GET:/options']); + }); + + test('should not auto-intercept non-preflight OPTIONS with network interception', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const key = `options-${Date.now()}-${Math.random()}`; + await browser.route('**/options?*', (route) => route.continue()); + const [text1, text2] = await browser.evaluate(`async (url) => { + const response1 = await fetch(url, { method: 'OPTIONS' }); + const text1 = await response1.text(); + const response2 = await fetch(url, { method: 'GET' }); + const text2 = await response2.text(); + return [text1, text2]; + }`, `${CROSS}/options?key=${key}`); + expect(text1).toBe('Hello'); + expect(text2).toBe('World'); + const requests = await browser.evaluate('(key) => fetch(`/options-log?key=${key}`).then((response) => response.json())', key); + expect(requests).toEqual(['OPTIONS:/options', 'GET:/options']); + }); + + test('should support cors with POST', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars', (route) => route.fulfill({ + contentType: 'application/json', + headers: { 'Access-Control-Allow-Origin': '*' }, + status: 200, + body: JSON.stringify(['electric', 'gas']), + })); + const resp = await browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + }); + return response.json(); + }`); + expect(resp).toEqual(['electric', 'gas']); + }); + + test('should support cors with credentials', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars', (route) => route.fulfill({ + contentType: 'application/json', + headers: { 'Access-Control-Allow-Origin': PREFIX, 'Access-Control-Allow-Credentials': 'true' }, + status: 200, + body: JSON.stringify(['electric', 'gas']), + })); + const resp = await browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + credentials: 'include', + }); + return response.json(); + }`); + expect(resp).toEqual(['electric', 'gas']); + }); + + test('should not abort preflighted cross-origin redirect when a route is registered', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/never-matches', (route) => route.continue()); + const result = await browser.evaluate(`async (url) => { + const response = await fetch(url, { credentials: 'include', headers: { 'X-App-Version': '1.2.3' } }); + const served = await response.json(); + return response.status + ' ' + served.method + ' ' + served.headers['x-app-version']; + }`, `${CROSS}/bounce?to=${encodeURIComponent(`${PREFIX}/cors-echo?preflight`)}`); + expect(result).toBe('200 GET 1.2.3'); + }); + + test('should reject cors with disallowed credentials', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars', (route) => route.fulfill({ + contentType: 'application/json', + headers: { 'Access-Control-Allow-Origin': PREFIX }, + status: 200, + body: JSON.stringify(['electric', 'gas']), + })); + const error = await browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + credentials: 'include', + }); + return response.json(); + }`).then(() => undefined, (caught: Error) => caught); + expect(error).toBeTruthy(); + }); + + test('should support cors for different methods', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.route('**/cars', (route) => route.fulfill({ + contentType: 'application/json', + headers: { 'Access-Control-Allow-Origin': '*' }, + status: 200, + body: JSON.stringify([route.request.method, 'electric', 'gas']), + })); + const post = await browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + mode: 'cors', + body: JSON.stringify({ number: 1 }), + }); + return response.json(); + }`); + expect(post).toEqual(['POST', 'electric', 'gas']); + const remove = await browser.evaluate(`async () => { + const response = await fetch('https://example.com/cars', { method: 'DELETE', headers: {}, mode: 'cors', body: '' }); + return response.json(); + }`); + expect(remove).toEqual(['DELETE', 'electric', 'gas']); + }); + + test('should contain raw request header', async ({ browser }) => { + let headers: Readonly> | undefined; + await browser.route('**/*', async (route) => { + headers = route.request.headers; + await route.continue(); + }); + await browser.goto('/empty.html'); + expect(headers?.['accept']).toBeTruthy(); + }); + + for (const method of ['fulfill', 'continue', 'fallback', 'abort'] as const) { + test(`route.${method} should throw if called twice`, async ({ browser }) => { + const handled = deferred(); + await browser.route('**/*', async (route) => { + const decide = (): Promise => (method === 'fulfill' ? route.fulfill({}) : route[method]()); + await decide(); + handled.resolve(await decide().then(() => new Error('decided twice'), (caught: Error) => caught)); + }); + const navigation = browser.goto('/empty.html').catch(() => undefined); + const e = await handled.promise; + expect(e.message).toContain('called twice'); + await navigation; + }); + } + + test('should intercept when postData is more than 1MB', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const intercepted = deferred(); + const POST_BODY = '0'.repeat(2 * 1024 * 1024); + await browser.route('**/404.html', async (route) => { + await route.abort(); + intercepted.resolve(route.request.postData); + }); + await browser.evaluate("(body) => fetch('/404.html', { method: 'POST', body }).then(() => null, () => null)", POST_BODY); + expect(await intercepted.promise).toBe(POST_BODY); + }); +}); diff --git a/apps/testbed/tests/screenshot.e2e.ts b/apps/testbed/tests/screenshot.e2e.ts new file mode 100644 index 0000000000..cc4637a347 --- /dev/null +++ b/apps/testbed/tests/screenshot.e2e.ts @@ -0,0 +1,447 @@ +/** + * Adapted from microsoft/playwright tests/page/page-screenshot.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `page.screenshot()` is `app.screenshot()`, read back with + * pngjs, and a `mask` is the `toHaveScreenshot` option, compared against the same viewport with + * boxes of the mask color painted over the masked elements. Playwright's golden images belong to + * its own renderer setup, so a golden comparison becomes a check of the pixels it shows. + */ + +/* + * Not ported: + * - should capture blinking caret if explicitly asked for: e2e has no `caret` option; its screenshots always hide the caret. + * - should clip rect: e2e has no `clip` option. + * - should clip rect with fullPage: e2e has no `clip` or `fullPage` option. + * - should clip elements to the viewport: e2e has no `clip` option. + * - should throw on clip outside the viewport: e2e has no `clip` option. + * - should throw on a negative clip size: e2e has no `clip` option. + * - should run in parallel: e2e has no `clip` option. + * - should take fullPage screenshots: e2e has no `fullPage` option. + * - should take fullPage screenshots and mask elements outside of it: e2e has no `fullPage` option. + * - should restore viewport after fullPage screenshot: e2e has no `fullPage` option. + * - should allow transparency: e2e has no `omitBackground` option. + * - should render white background on jpeg file: e2e screenshots are PNG only. + * - should produce a valid webp screenshot: e2e screenshots are PNG only. + * - path option should detect webp: e2e has no `path` or `type` option. + * - quality option should work for webp: e2e has no `quality` option. + * - webp screenshots should be lossless by default: e2e screenshots are PNG only. + * - should allow transparency with webp: e2e has no `omitBackground` option. + * - quality option should throw for webp when out of range: e2e has no `quality` option. + * - should work with odd clip size on Retina displays: e2e has no `clip` option or device scale factor. + * - should work for webgl: golden only, and headless WebGL renders differently per GPU backend. + * - path option should work: e2e has no `path` option. + * - path option should create subdirectories: e2e has no `path` option. + * - path option should detect jpeg: e2e has no `path` option. + * - path option should throw for unsupported mime type: e2e has no `path` option. + * - quality option should throw for png: e2e has no `quality` option. + * - zero quality option should throw for png: e2e has no `quality` option. + * - quality option should work for jpeg: e2e has no `quality` option. + * - should prefer type over extension: e2e has no `path` or `type` option. + * - should take fullPage screenshots during navigation: e2e has no `fullPage` option. + * - mask option should work with elementhandle: element handles. + * - mask option should hide elements based on attr: e2e has no `style` option. + * - mask option should remove elements based on attr: e2e has no `style` option. + * - page screenshot animations (all 13 tests): e2e has no `animations` option. + * - should throw if screenshot size is too large: e2e has no `fullPage` option. + * - page screenshot should capture css transform: golden only, of a 3D transform with no stable pixel to check. + * The `fullPage` option of should work while navigating and should work with Array deleted is dropped: they take the viewport. + */ + +import { copyFileSync, mkdirSync, readFileSync, rmSync } from 'node:fs'; +import path from 'node:path'; +import { test, type Browser, type WebApp } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { PNG } from 'pngjs'; +import { content, CROSS, PREFIX } from './helpers.ts'; + +const stored = new Set(); + +/** One element a mask covers: a selector and its match index, inside the iframe `frame` matches when set. */ +interface MaskTarget { + readonly frame?: string; + readonly selector: string; + readonly index: number; +} + +/** The PNG at `file`, decoded. */ +function readPng(file: string): PNG { + return PNG.sync.read(readFileSync(file)); +} + +/** The red, green, and blue of the pixel at (`x`, `y`). */ +function rgb(png: PNG, x: number, y: number): [number, number, number] { + const offset = (y * png.width + x) * 4; + return [png.data[offset]!, png.data[offset + 1]!, png.data[offset + 2]!]; +} + +/** Whether two colors are the same within `slack` per channel. */ +function near(actual: readonly number[], expected: readonly number[], slack = 3): boolean { + return actual.every((value, index) => Math.abs(value - expected[index]!) <= slack); +} + +/** The pixels of `box` cut out of `png`, rounded out to whole pixels. */ +function crop(png: PNG, box: { x: number; y: number; width: number; height: number }): Buffer { + const left = Math.floor(box.x); + const top = Math.floor(box.y); + const right = Math.ceil(box.x + box.width); + const bottom = Math.ceil(box.y + box.height); + const rows: Buffer[] = []; + for (let y = top; y < bottom; y++) rows.push(png.data.subarray((y * png.width + left) * 4, (y * png.width + right) * 4)); + return Buffer.concat(rows); +} + +/** Where `toHaveScreenshot(name)` in this file reads its stored screenshot on the `web` target. */ +function storedPath(name: string): string { + return path.join(import.meta.dirname, 'screenshot.e2e.ts-snapshots', `${name}-web-${process.platform}.png`); +} + +/** + * Paints a `color` box over each of `targets`, as a `mask` would cover it, keeps the viewport as + * the stored screenshot `name`, then takes the boxes away. + */ +async function storeMaskedReference(browser: Browser, app: WebApp, name: string, targets: readonly MaskTarget[], color = '#ff00ff'): Promise { + await browser.evaluate(`({ targets, color }) => { + for (const { frame, selector, index } of targets) { + const host = frame === undefined ? undefined : document.querySelector(frame); + const origin = host === undefined ? { left: 0, top: 0 } : host.getBoundingClientRect(); + const offset = host === undefined ? { left: 0, top: 0 } : { left: host.clientLeft, top: host.clientTop }; + const element = (host === undefined ? document : host.contentDocument).querySelectorAll(selector)[index]; + const rect = element.getBoundingClientRect(); + const box = document.createElement('div'); + box.setAttribute('data-test-mask', ''); + box.style.cssText = 'position: fixed; z-index: 2147483647; pointer-events: none; margin: 0; border: 0; padding: 0;'; + box.style.left = (origin.left + offset.left + rect.left) + 'px'; + box.style.top = (origin.top + offset.top + rect.top) + 'px'; + box.style.width = rect.width + 'px'; + box.style.height = rect.height + 'px'; + box.style.background = color; + document.documentElement.appendChild(box); + } + }`, { targets: targets.map((target) => ({ ...target })), color }); + await storeReference(app, name); + await browser.evaluate("() => { for (const box of document.querySelectorAll('[data-test-mask]')) box.remove(); }"); +} + +/** Keeps the viewport, as `app.screenshot` takes it, as the stored screenshot `name` until the test ends. */ +async function storeReference(app: WebApp, name: string): Promise { + const file = storedPath(name); + mkdirSync(path.dirname(file), { recursive: true }); + stored.add(file); + copyFileSync(await app.screenshot(name), file); +} + +/** Appends an iframe with `id` loading `url`, Playwright's `attachFrame`, once it has loaded. */ +async function attachFrame(browser: Browser, id: string, url: string): Promise { + await browser.evaluate(`async ({ id, url }) => { + const frame = document.createElement('iframe'); + frame.src = url; + frame.id = id; + document.body.appendChild(frame); + await new Promise((x) => (frame.onload = x)); + }`, { id, url }); +} + +/** Adds a ` +
+ `)); + const div = browser.locator('div'); + await div.pressSequentially('foo bar'); + const box = (await div.boundingBox())!; + const screenshot = crop(readPng(await app.screenshot()), box); + for (let i = 0; i < 10; ++i) { + await new Promise((x) => setTimeout(x, 150)); + const newScreenshot = crop(readPng(await app.screenshot()), box); + expect(newScreenshot.equals(screenshot)).toBe(true); + } + }); + + test('should capture blinking caret in shadow dom', async ({ app, browser }) => { + await browser.goto('/empty.html'); + await browser.evaluate(`() => { + class CustomElementContainer extends HTMLElement { + #shadowRoot; + constructor() { + super(); + this.#shadowRoot = this.attachShadow({ mode: 'open' }); + this.#shadowRoot.innerHTML = ''; + } + } + class CustomElementInputWrapper extends HTMLElement { + #shadowRoot; + constructor() { + super(); + this.#shadowRoot = this.attachShadow({ mode: 'open' }); + this.#shadowRoot.innerHTML = ''; + } + } + customElements.define('custom-element-input-wrapper', CustomElementInputWrapper); + customElements.define('custom-element-container', CustomElementContainer); + + const container = document.createElement('custom-element-container'); + document.body.appendChild(container); + }`); + + const input = browser.locator('input'); + await input.focus(); + + const box = (await input.boundingBox())!; + const screenshot = crop(readPng(await app.screenshot()), box); + let hasDifferentScreenshots = false; + for (let i = 0; !hasDifferentScreenshots && i < 10; ++i) { + await new Promise((x) => setTimeout(x, 150)); + const newScreenshot = crop(readPng(await app.screenshot()), box); + hasDifferentScreenshots = !newScreenshot.equals(screenshot); + } + expect(hasDifferentScreenshots).toBe(false); + }); + + test('should work for canvas', async ({ app, browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/screenshots/canvas.html'); + const screenshot = readPng(await app.screenshot()); + expect(rgb(screenshot, 8 + 30, 8 + 30)).toEqual([0, 0, 0]); + expect(rgb(screenshot, 8 + 120, 8 + 120)).toEqual([0, 0, 0]); + expect(rgb(screenshot, 8 + 60, 8 + 60)).toEqual([255, 255, 255]); + expect(rgb(screenshot, 8 + 75, 8 + 75)).toEqual([255, 255, 255]); + expect(rgb(screenshot, 8 + 140, 8 + 140)).toEqual([255, 255, 255]); + }); + + test('should capture canvas changes', async ({ app, browser }) => { + await browser.goto(content('')); + await browser.evaluate(`() => { + const canvas = document.querySelector('canvas'); + canvas.width = 600; + canvas.height = 600; + }`); + + /** Draws the horizontal line of `step`, 100 pixels below the one before. */ + async function addLine(step: number): Promise { + await browser.evaluate(`(n) => { + const canvas = document.querySelector('canvas'); + const ctx = canvas.getContext('2d'); + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.moveTo(0, n * 100); + ctx.lineTo(300, n * 100); + ctx.stroke(); + }`, step); + } + + /** Whether the line of `step` shows in `screenshot`: the canvas sits at the body margin, 8 pixels in. */ + function hasLine(screenshot: PNG, step: number): boolean { + const y = 8 + step * 100; + return [y - 1, y].some((row) => row >= 8 && rgb(screenshot, 8 + 150, row)[0] < 200); + } + + for (let i = 0; i < 3; i++) { + await addLine(i); + await new Promise((f) => setTimeout(f, 100)); + const screenshot = readPng(await app.screenshot()); + for (let step = 0; step < 3; step++) expect(hasLine(screenshot, step)).toBe(step <= i); + } + }); + + test('should work for translateZ', async ({ app, browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/screenshots/translateZ.html'); + const screenshot = readPng(await app.screenshot()); + expect(rgb(screenshot, 120, 120)).toEqual([255, 0, 0]); + expect(rgb(screenshot, 175, 175)).toEqual([0, 128, 0]); + expect(rgb(screenshot, 230, 230)).toEqual([0, 128, 0]); + expect(rgb(screenshot, 300, 300)).toEqual([255, 255, 255]); + }); + + test('should work while navigating', { skip: 'a screenshot taken while the page navigates fails as stale instead of capturing whichever document shows (an engine failure, which `fail` does not cover)' }, async ({ app, browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/redirectloop1.html'); + for (let i = 0; i < 10; i++) { + const screenshot = readPng(await app.screenshot()); + expect([screenshot.width, screenshot.height]).toEqual([500, 500]); + } + }); + + test('should work with iframe in shadow', async ({ app, browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid-iframe-in-shadow.html'); + await expect(browser.frameLocator('iframe').locator('div').first()).toBeVisible(); + const screenshot = readPng(await app.screenshot()); + expect(near(rgb(screenshot, 3, 3), [255, 204, 204])).toBe(true); + expect(rgb(screenshot, 400, 400)).toEqual([255, 255, 255]); + }); + + test('should not issue resize event', async ({ app, browser }) => { + await browser.goto('/grid.html'); + await browser.evaluate("() => { window.__resized = false; window.addEventListener('resize', () => { window.__resized = true; }); }"); + await app.screenshot(); + expect(await browser.evaluate('window.__resized')).toBe(false); + }); + + test('should work with Array deleted', { fail: 'the evaluate wrapper needs the page\'s `Array`' }, async ({ app, browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await browser.evaluate('() => { delete window.Array; }'); + const screenshot = readPng(await app.screenshot()); + expect([screenshot.width, screenshot.height]).toEqual([500, 500]); + expect(near(rgb(screenshot, 3, 3), [255, 204, 204])).toBe(true); + }); + + test.describe('mask option', () => { + test('should work', async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await storeMaskedReference(browser, app, 'mask-should-work', [{ selector: 'div', index: 5 }]); + await expect(screen).toHaveScreenshot('mask-should-work', { + mask: [browser.locator('div').nth(5)], + }); + }); + + test('should work with locator', async ({ app, browser }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await storeMaskedReference(browser, app, 'mask-should-work-with-locator', [{ selector: 'div', index: 5 }]); + const bodyLocator = browser.locator('body'); + await expect(bodyLocator).toHaveScreenshot('mask-should-work-with-locator', { + mask: [browser.locator('div').nth(5)], + }); + }); + + test('should mask multiple elements', async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await storeMaskedReference(browser, app, 'should-mask-multiple-elements', [{ selector: 'div', index: 5 }, { selector: 'div', index: 12 }]); + await expect(screen).toHaveScreenshot('should-mask-multiple-elements', { + mask: [ + browser.locator('div').nth(5), + browser.locator('div').nth(12), + ], + }); + }); + + test('should mask inside iframe', async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await attachFrame(browser, 'frame1', `${PREFIX}/grid.html`); + await addStyleTag(browser, 'iframe { border: none; }'); + await storeMaskedReference(browser, app, 'should-mask-inside-iframe', [{ selector: 'div', index: 5 }, { frame: '#frame1', selector: 'div', index: 12 }]); + await expect(screen).toHaveScreenshot('should-mask-inside-iframe', { + mask: [ + browser.locator('div').nth(5), + browser.frameLocator('#frame1').locator('div').nth(12), + ], + }); + }); + + test('should mask in parallel', { fail: 'two screenshot steps at once interfere: one finds its mask node stale' }, async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/empty.html'); + await attachFrame(browser, 'frame1', `${PREFIX}/grid.html`); + await attachFrame(browser, 'frame2', `${PREFIX}/grid.html`); + await addStyleTag(browser, 'iframe { border: none; }'); + await storeMaskedReference(browser, app, 'should-mask-in-parallel-1', [{ frame: '#frame1', selector: 'div', index: 1 }]); + await storeMaskedReference(browser, app, 'should-mask-in-parallel-2', [{ frame: '#frame2', selector: 'div', index: 3 }]); + const results = await Promise.allSettled([ + expect(screen).toHaveScreenshot('should-mask-in-parallel-1', { + mask: [browser.frameLocator('#frame1').locator('div').nth(1)], + }), + expect(screen).toHaveScreenshot('should-mask-in-parallel-2', { + mask: [browser.frameLocator('#frame2').locator('div').nth(3)], + }), + ]); + for (const result of results) if (result.status === 'rejected') throw result.reason; + }); + + test('should remove mask after screenshot', async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + const screenshot1 = readFileSync(await app.screenshot()); + await storeMaskedReference(browser, app, 'should-remove-mask-after-screenshot', [{ selector: 'div', index: 1 }]); + await expect(screen).toHaveScreenshot('should-remove-mask-after-screenshot', { + mask: [browser.locator('div').nth(1)], + }); + const screenshot2 = readFileSync(await app.screenshot()); + expect(screenshot1.equals(screenshot2)).toBe(true); + }); + + test('should work when subframe has stalled navigation', { skip: 'no screenshot comes back while a subframe navigation stalls (an engine failure, which `fail` does not cover)' }, async ({ app, browser, screen }) => { + let routed!: () => void; + const routeReady = new Promise((f) => (routed = f)); + let release!: () => void; + const released = new Promise((f) => (release = f)); + await browser.route('**/subframe.html', async (route) => { + routed(); + await released; + await route.fulfill({ body: '' }); + }); + + await browser.goto(content('')); + await storeReference(app, 'mask-stalled-subframe'); + await browser.goto(content(``), { waitUntil: 'domcontentloaded' }); + await routeReady; + + await expect(screen).toHaveScreenshot('mask-stalled-subframe', { mask: [browser.locator('non-existent')] }); + release(); + await expect(browser.frameLocator('iframe').locator('body')).toBeAttached(); + }); + + test('should work when subframe used document.open after a weird url', async ({ app, browser, screen }) => { + await browser.goto('/empty.html'); + await browser.evaluate(`() => { + const iframe = document.createElement('iframe'); + iframe.src = 'javascript:hi'; + document.body.appendChild(iframe); + iframe.contentDocument.open(); + iframe.contentDocument.write('Hello'); + iframe.contentDocument.close(); + }`); + await storeReference(app, 'mask-document-open'); + await expect(screen).toHaveScreenshot('mask-document-open', { mask: [browser.locator('non-existent')] }); + }); + + test('should work when mask color is not pink #F0F', async ({ app, browser, screen }) => { + await browser.setViewport({ width: 500, height: 500 }); + await browser.goto('/grid.html'); + await storeMaskedReference(browser, app, 'mask-color-should-work', [{ selector: 'div', index: 5 }], '#00ff00'); + await expect(screen).toHaveScreenshot('mask-color-should-work', { + mask: [browser.locator('div').nth(5)], + maskColor: '#00FF00', + }); + }); + }); +}); + +test('should capture css box-shadow', { requires: ['browser'], tags: ['playwright'] }, async ({ app, browser }) => { + await browser.goto(content(`
`)); + const screenshot = readPng(await app.screenshot()); + expect(rgb(screenshot, 30, 30)).toEqual([255, 255, 255]); + expect(rgb(screenshot, 62, 40)[0]).toBe(255); + expect(rgb(screenshot, 62, 40)[1]).toBeLessThan(200); + expect(rgb(screenshot, 100, 100)).toEqual([255, 255, 255]); +}); diff --git a/apps/testbed/tests/select-option.e2e.ts b/apps/testbed/tests/select-option.e2e.ts new file mode 100644 index 0000000000..f263659862 --- /dev/null +++ b/apps/testbed/tests/select-option.e2e.ts @@ -0,0 +1,283 @@ +/** + * Adapted from microsoft/playwright tests/page/page-select-option.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `page.selectOption(selector, value)` is a locator selectOption. + */ + +/* + * Not ported: + * - should select single option by handle: no element handles. + * - should select single option by multiple attributes: `selectOption` takes one of label, value, or index. + * - should not select single option when some attributes do not match: `selectOption` takes one of label, value, or index. + * - should select only first option: `selectOption` takes one option, no arrays. + * - should select multiple options: `selectOption` takes one option, no arrays. + * - should select multiple options with attributes: `selectOption` takes one option, no arrays. + * - should return [] on no matched values: `selectOption` returns nothing and takes no arrays. + * - should return an array of matched values: `selectOption` returns nothing and takes no arrays. + * - should return an array of one element when multiple is not set: `selectOption` returns nothing and takes no arrays. + * - should return [] on no values: `selectOption` returns nothing and takes no arrays. + * - should not allow null items: no arrays or null. + * - should unselect with null: no arrays or null. + * - should deselect all options when passed no values for a multiple select: no arrays. + * - should deselect all options when passed no values for a select without multiple: no arrays. + * - should throw if passed wrong types: asserts Playwright's protocol validator messages; the option is typed. + * - should wait for multiple options to be present: `selectOption` takes one option, no arrays. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +/** Five pairs of animation frames, Playwright's `rafraf(page, 5)`, so a pending select has had its chance. */ +const giveItAChanceToResolve = '() => new Promise((resolve) => { let frames = 0; const step = () => (++frames === 10 ? setTimeout(resolve, 0) : requestAnimationFrame(step)); requestAnimationFrame(step); })'; + +/** Appends a `scarlet` option to the page's select. */ +const addScarlet = "() => { const option = document.createElement('option'); option.value = 'scarlet'; option.textContent = 'Scarlet'; document.querySelector('select').appendChild(option); }"; + +test.describe('page select option', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should select single option', { fail: 'a bare string selects by label only, where Playwright matches the value or the label', timeout: 5000 }, async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption('blue'); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['blue']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['blue']); + }); + + test('should select single option by value', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption({ value: 'blue' }); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['blue']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['blue']); + }); + + test('should fall back to selecting by label', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption('Blue'); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['blue']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['blue']); + }); + + test('should select single option by label', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption({ label: 'Indigo' }); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['indigo']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['indigo']); + }); + + test('should select single option by label with html whitespace', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption({ label: 'HTML' }); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['html']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['html']); + }); + + test('should select single option by index', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption({ index: 2 }); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['brown']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['brown']); + }); + + test('should not throw when select causes navigation', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.evaluate("() => document.querySelector('select').addEventListener('input', () => window.location.href = '/empty.html')"); + await Promise.all([ + browser.locator('select').selectOption({ value: 'blue' }), + browser.waitForURL(/empty\.html/), + ]); + expect(await browser.url()).toContain('empty.html'); + }); + + test('should respect event bubbling', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.locator('select').selectOption({ value: 'blue' }); + expect(await browser.evaluate('() => window.result.onBubblingInput')).toEqual(['blue']); + expect(await browser.evaluate('() => window.result.onBubblingChange')).toEqual(['blue']); + }); + + test('should throw when element is not a element'); + }); + + test('should work when re-defining top-level Event class', async ({ browser }) => { + await browser.goto('/input/select.html'); + await browser.evaluate('() => { window.Event = null; }'); + await browser.locator('select').selectOption({ value: 'blue' }); + expect(await browser.evaluate('() => window.result.onInput')).toEqual(['blue']); + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['blue']); + }); + + test('should wait for option to be present', async ({ browser }) => { + await browser.goto('/input/select.html'); + const selectPromise = browser.locator('select').selectOption({ value: 'scarlet' }, { timeout: 10_000 }); + let didSelect = false; + void selectPromise.then(() => (didSelect = true)); + await browser.evaluate(giveItAChanceToResolve); + expect(didSelect).toBe(false); + await browser.evaluate(addScarlet); + await selectPromise; + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['scarlet']); + }); + + test('should wait for option index to be present', async ({ browser }) => { + await browser.goto('/input/select.html'); + const len = await browser.evaluate("() => document.querySelector('select').options.length"); + const selectPromise = browser.locator('select').selectOption({ index: len }, { timeout: 10_000 }); + let didSelect = false; + void selectPromise.then(() => (didSelect = true)); + await browser.evaluate(giveItAChanceToResolve); + expect(didSelect).toBe(false); + await browser.evaluate(addScarlet); + await selectPromise; + expect(await browser.evaluate('() => window.result.onChange')).toEqual(['scarlet']); + }); + + test('input event.composed should be true and cross shadow dom boundary', async ({ browser }) => { + await browser.goto('/empty.html'); + await browser.goto(content(``)); + await browser.evaluate(`() => { + window.firedBodyEvents = []; + for (const event of ['input', 'change']) + document.body.addEventListener(event, (e) => window.firedBodyEvents.push(e.type + ':' + e.composed), false); + }`); + await browser.evaluate(`() => { + window.firedEvents = []; + const select = document.querySelector('div').shadowRoot.querySelector('select'); + for (const event of ['input', 'change']) + select.addEventListener(event, (e) => window.firedEvents.push(e.type + ':' + e.composed), false); + }`); + await browser.locator('select').selectOption({ value: 'blue' }); + expect(await browser.evaluate('firedEvents')).toEqual(['input:true', 'change:false']); + expect(await browser.evaluate('firedBodyEvents')).toEqual(['input:true']); + }); + + test('should wait for select to be enabled', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + const selectPromise = browser.locator('select').selectOption('two'); + await new Promise((resolve) => setTimeout(resolve, 1000)); + await browser.evaluate('() => window.hydrate()'); + await selectPromise; + expect(await browser.evaluate('result')).toEqual('two'); + await expect(browser.locator('select')).toHaveValue('two'); + }); + + test('should wait for option to be enabled', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + const error = await browser.locator('select').selectOption('two', { timeout: 1000 }).catch((caught: Error) => caught); + expect((error as Error).message).toContain('option being selected is not enabled'); + + const selectPromise = browser.locator('select').selectOption('two'); + await new Promise((resolve) => setTimeout(resolve, 1000)); + await browser.evaluate('() => window.hydrate()'); + await selectPromise; + expect(await browser.evaluate('result')).toEqual('two'); + await expect(browser.locator('select')).toHaveValue('two'); + }); + + test('should wait for optgroup to be enabled', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + const error = await browser.locator('select').selectOption('two', { timeout: 1000 }).catch((caught: Error) => caught); + expect((error as Error).message).toContain('option being selected is not enabled'); + + const selectPromise = browser.locator('select').selectOption('two'); + await new Promise((resolve) => setTimeout(resolve, 1000)); + await browser.evaluate('() => window.hydrate()'); + await selectPromise; + expect(await browser.evaluate('result')).toEqual('two'); + await expect(browser.locator('select')).toHaveValue('two'); + }); + + test('should wait for select to be swapped', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + const selectPromise = browser.locator('select').selectOption('two'); + await new Promise((resolve) => setTimeout(resolve, 1000)); + await browser.evaluate('() => window.hydrate()'); + await selectPromise; + await expect(browser.locator('select')).toHaveValue('two'); + expect(await browser.evaluate('result')).toEqual('two'); + }); +}); diff --git a/apps/testbed/tests/selectors-frame.e2e.ts b/apps/testbed/tests/selectors-frame.e2e.ts new file mode 100644 index 0000000000..fa6948d63a --- /dev/null +++ b/apps/testbed/tests/selectors-frame.e2e.ts @@ -0,0 +1,164 @@ +/** + * Adapted from microsoft/playwright tests/page/selectors-frame.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `iframe >> internal:control=enter-frame >> x` is + * `frameLocator('iframe').locator(x)`, `:has-text()` a `hasText` filter, and the routed frame + * pages are pages the server serves (`content()`). + */ + +/* + * Not ported: + * - should work for iframe (handle): element handles. + * - should work for nested iframe (handle): element handles. + * - should work for $ and $$ (handle): element handles. + * - should work for $eval (handle): element handles. + * - should work for $$eval (handle): element handles. + * - waitForSelector should survive frame reattach (handle): element handles. + * - waitForSelector should survive iframe navigation (handle): element handles. + * - $eval should throw for missing frame: asserts Playwright's `$eval` error text; e2e has no `$eval`. + * - should not allow dangling enter-frame: Playwright selector syntax, which e2e locators do not take. + * - should not allow leading enter-frame: Playwright selector syntax. + * - should not allow capturing before enter-frame: Playwright selector syntax. + * - should capture after the enter-frame: Playwright selector syntax (`*css=`) and innerHTML. + * - should non work for non-frame: asserts Playwright's error text naming the matched `
`. + * - should match in a descendant frame: `internal:control=any-frame` has no e2e counterpart. + * - should match in a deeply nested frame: `internal:control=any-frame`. + * - should not match a chain across frames: `internal:control=any-frame`. + * - should match multiple elements: `internal:control=any-frame`. + * - should throw when matching elements in multiple frames: `internal:control=any-frame` and page.frames(). + * - should not allow any-frame in the middle of a selector: `internal:control=any-frame`. + * - should allow entering frames from any frame: `internal:control=any-frame`. + * - should not allow any-frame after entering a frame: `internal:control=any-frame`. + * - should not allow dangling enter-frame after any-frame: `internal:control=any-frame`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +const iframe2 = content(''); + +const iframe = content(` + +
+ + +
+ 1 + 2 + `); + +const routed = content(``); + +/** Waits `ms` milliseconds. */ +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +test.describe('selectors frame', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should work for iframe', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button'); + await button.waitFor(); + expect(await button.textContent()).toBe('Hello iframe'); + await expect(button).toHaveText('Hello iframe'); + await button.tap(); + }); + + test('should work for nested iframe', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').frameLocator('iframe').locator('button'); + await button.waitFor(); + expect(await button.textContent()).toBe('Hello nested iframe'); + await expect(button).toHaveText('Hello nested iframe'); + await button.tap(); + }); + + test('should work for $ and $$', async ({ browser }) => { + await browser.goto(routed); + const element = browser.frameLocator('iframe').locator('button'); + await element.waitFor({ state: 'attached' }); + expect(await element.textContent()).toBe('Hello iframe'); + await browser.frameLocator('iframe').locator('span').nth(1).waitFor({ state: 'attached' }); + expect(await browser.frameLocator('iframe').locator('span').count()).toBe(2); + }); + + test('$ should not wait for frame', async ({ browser }) => { + await browser.goto('/empty.html'); + expect(await browser.frameLocator('iframe').locator('canvas').count()).toBe(0); + }); + + test('$$ should not wait for frame', async ({ browser }) => { + await browser.goto('/empty.html'); + expect(await browser.frameLocator('iframe').locator('canvas').all()).toHaveLength(0); + }); + + test('$$eval should not throw for missing frame', async ({ browser }) => { + await browser.goto('/empty.html'); + expect(await browser.frameLocator('iframe').locator('canvas').allTextContents()).toHaveLength(0); + }); + + test('should work for $eval', async ({ browser }) => { + await browser.goto(routed); + await expect(browser.frameLocator('iframe').getByRole('button')).toHaveCount(1); + await expect(browser.frameLocator('iframe').locator('button')).toHaveCount(1); + }); + + test('should work for $$eval', async ({ browser }) => { + await browser.goto(routed); + await expect(browser.frameLocator('iframe').locator('span')).toHaveCount(2); + expect(await browser.frameLocator('iframe').locator('span').allTextContents()).toEqual(['1', '2']); + }); + + test('should click in lazy iframe', async ({ browser }) => { + const lazy = content(''); + await browser.goto('/empty.html'); + const attached = delay(500) + .then(() => browser.evaluate("() => { document.body.appendChild(document.createElement('iframe')); }")) + .then(() => delay(500)) + .then(() => browser.evaluate("(src) => { document.querySelector('iframe').src = src; }", lazy)); + const button = browser.frameLocator('iframe').locator('button'); + const [, text] = await Promise.all([ + button.tap(), + button.textContent(), + expect(button).toHaveText('Hello iframe'), + attached, + ]); + expect(text).toBe('Hello iframe'); + }); + + test('waitFor should survive frame reattach', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.waitFor(); + await browser.evaluate("() => { document.querySelector('iframe').remove(); }"); + await browser.evaluate("(src) => { const iframe = document.createElement('iframe'); iframe.src = src; document.body.appendChild(iframe); }", iframe2); + await promise; + }); + + test('click should survive frame reattach', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.tap(); + await browser.evaluate("() => { document.querySelector('iframe').remove(); }"); + await browser.evaluate("(src) => { const iframe = document.createElement('iframe'); iframe.src = src; document.body.appendChild(iframe); }", iframe2); + await promise; + }); + + test('click should survive iframe navigation', async ({ browser }) => { + await browser.goto(routed); + const button = browser.frameLocator('iframe').locator('button').filter({ hasText: 'Hello nested iframe' }); + const promise = button.tap(); + const navigated = browser.evaluate("(src) => { document.querySelector('iframe').src = src; }", iframe2); + await promise; + await navigated; + }); + + test('click should survive navigation', async ({ browser }) => { + await browser.goto(iframe); + const promise = browser.locator('button').filter({ hasText: 'Hello nested iframe' }).tap(); + await delay(100); + await browser.goto(iframe2); + await promise; + }); +}); diff --git a/apps/testbed/tests/selectors-get-by.e2e.ts b/apps/testbed/tests/selectors-get-by.e2e.ts new file mode 100644 index 0000000000..2f6737c885 --- /dev/null +++ b/apps/testbed/tests/selectors-get-by.e2e.ts @@ -0,0 +1,217 @@ +/** + * Adapted from microsoft/playwright tests/page/selectors-get-by.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: a string query is exact by default, + * so Playwright's default substring match is `{ exact: false }` and its + * `{ exact: true }` is the default; `evaluate(e => e.outerHTML)` reads become + * text and attribute reads of the match. + * + * Not ported: + * - getByTestId with custom testId should work: the test id attribute is project config, not per test. + * - getByTestId with comma-separated testIdAttributes should match any: same. + * - getByAltText should work: e2e has no getByAltText. + * - getByTitle should work: e2e has no getByTitle. + * - getByRole with description: e2e getByRole has no description option. + * - getByRole with description via aria-describedby: same. + * - getByRole with description via title fallback: same. + * - getByRole with description whitespace normalization: same. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('selectors get by', { requires: ['browser'], tags: ['playwright'] }, () => { + test('getByTestId should work', async ({ screen, browser }) => { + await browser.goto(content('
Hello world
')); + await expect(screen.getByTestId('Hello')).toHaveText('Hello world'); + await expect(browser.locator('div').getByTestId('Hello')).toHaveText('Hello world'); + }); + + test('getByTestId should escape id', async ({ screen, browser }) => { + await browser.goto(content(`
Hello world
`)); + await expect(screen.getByTestId('He"llo')).toHaveText('Hello world'); + }); + + test('getByTestId should work for regex', async ({ screen, browser }) => { + await browser.goto(content('
Hello world
')); + await expect(screen.getByTestId(/He[l]*o/)).toHaveText('Hello world'); + await expect(browser.locator('div').getByTestId('Hello')).toHaveText('Hello world'); + }); + + test('getByText should work', async ({ screen, browser }) => { + await browser.goto(content(`
yo
ya
\nye
`)); + expect(await screen.getByText('ye', { exact: false }).textContent()).toBe('ye'); + expect(await screen.getByText(/ye/).textContent()).toBe('ye'); + expect(await screen.getByText(/e/).textContent()).toBe('ye'); + + await browser.goto(content(`
ye
ye
`)); + expect(await screen.getByText('ye').first().boundingBox()).toEqual(await browser.locator('div').first().boundingBox()); + + await browser.goto(content(`
Hello world
Hello
`)); + expect(await screen.getByText('Hello').textContent()).toBe('Hello'); + }); + + test('getByLabel should work', async ({ screen, browser }) => { + await browser.goto(content(`
`)); + expect(await screen.getByText('Name', { exact: false }).getAttribute('for')).toBe('target'); + expect(await screen.getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + expect(await browser.locator('div').getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should work with nested elements', async ({ screen, browser }) => { + await browser.goto(content(``)); + + await expect(screen.getByLabel('last name', { exact: false })).toHaveAttribute('id', 'target'); + await expect(screen.getByLabel('st na', { exact: false })).toHaveAttribute('id', 'target'); + await expect(screen.getByLabel('Name', { exact: false })).toHaveAttribute('id', 'target'); + await expect(screen.getByLabel('Last Name')).toHaveAttribute('id', 'target'); + await expect(screen.getByLabel(/Last\s+name/i)).toHaveAttribute('id', 'target'); + + expect(await screen.getByLabel('Last').count()).toBe(0); + expect(await screen.getByLabel('last name').count()).toBe(0); + expect(await screen.getByLabel('Name').count()).toBe(0); + expect(await screen.getByLabel('what?', { exact: false }).count()).toBe(0); + expect(await screen.getByLabel(/last name/).count()).toBe(0); + }); + + test('getByLabel should work with multiply-labelled input', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + expect(await screen.getByLabel('First or Last', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should work with ancestor label and multiple controls', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should work with ancestor label and for', async ({ screen, browser }) => { + await browser.goto(content(` + + + `)); + expect(await screen.getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should work with aria-labelledby', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Name', { exact: false }).textContent()).toBe('Click me'); + }); + + test('getByLabel should prioritize aria-labelledby over native label', async ({ screen, browser }) => { + await browser.goto(content(` + + + `)); + expect(await screen.getByLabel('Name', { exact: false }).textContent()).toBe('Click me'); + }); + + test('getByLabel should work with aria-label', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Name', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should ignore empty aria-label', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Last Name', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByLabel should prioritize aria-labelledby over aria-label', async ({ screen, browser }) => { + await browser.goto(content(``)); + expect(await screen.getByLabel('Other', { exact: false }).getAttribute('id')).toBe('target'); + }); + + test('getByPlaceholder should work', async ({ screen, browser }) => { + await browser.goto(content(`
+ + +
`)); + await expect(screen.getByPlaceholder('hello', { exact: false })).toHaveCount(2); + await expect(screen.getByPlaceholder('Hello')).toHaveCount(1); + await expect(screen.getByPlaceholder(/wor/i)).toHaveCount(1); + + await expect(browser.locator('div').getByPlaceholder('hello', { exact: false })).toHaveCount(2); + }); + + test('getBy escaping', async ({ screen, browser }) => { + const setAttributes = "(value) => { const input = document.querySelector('input'); for (const name of ['placeholder', 'title', 'alt']) input.setAttribute(name, value); }"; + + await browser.goto(content(``)); + await browser.evaluate(setAttributes, 'hello my\nwo"rld'); + await expect.soft(screen.getByText('hello my\nwo"rld', { exact: false })).toHaveAttribute('id', 'label'); + await expect.soft(screen.getByText('hello my wo"rld', { exact: false })).toHaveAttribute('id', 'label'); + await expect.soft(screen.getByLabel('hello my\nwo"rld', { exact: false })).toHaveAttribute('id', 'control'); + await expect.soft(screen.getByPlaceholder('hello my\nwo"rld', { exact: false })).toHaveAttribute('id', 'control'); + + await browser.goto(content(``)); + await browser.evaluate(setAttributes, 'hello my\nworld'); + await expect.soft(screen.getByText('hello my\nworld', { exact: false })).toHaveAttribute('id', 'label'); + await expect.soft(screen.getByText('hello my world', { exact: false })).toHaveAttribute('id', 'label'); + await expect.soft(screen.getByLabel('hello my\nworld', { exact: false })).toHaveAttribute('id', 'control'); + await expect.soft(screen.getByPlaceholder('hello my\nworld', { exact: false })).toHaveAttribute('id', 'control'); + + await browser.goto(content(``)); + await browser.evaluate(setAttributes, 'foo >> bar'); + expect.soft(await screen.getByText('foo >> bar', { exact: false }).textContent()).toBe('foo >> bar'); + await expect.soft(browser.locator('label')).toHaveText('foo >> bar'); + await expect.soft(screen.getByText('foo >> bar', { exact: false })).toHaveText('foo >> bar'); + expect.soft(await screen.getByText(/foo >> bar/).textContent()).toBe('foo >> bar'); + await expect.soft(screen.getByLabel('foo >> bar', { exact: false })).toHaveAttribute('id', 'target'); + await expect.soft(screen.getByLabel(/foo >> bar/)).toHaveAttribute('id', 'target'); + await expect.soft(screen.getByPlaceholder('foo >> bar', { exact: false })).toHaveAttribute('id', 'target'); + await expect.soft(screen.getByPlaceholder(/foo >> bar/)).toHaveAttribute('id', 'target'); + }); + + test('getByRole escaping', async ({ screen, browser }) => { + await browser.goto(content(` + issues 123 + he llo 56 + + `)); + expect.soft(await screen.getByRole('button').allTextContents()).toEqual(['Click me']); + expect.soft(await screen.getByRole('link').allTextContents()).toEqual(['issues 123', 'he llo 56']); + + expect.soft(await screen.getByRole('link', { name: 'issues 123', exact: false }).allTextContents()).toEqual(['issues 123']); + expect.soft(await screen.getByRole('link', { name: 'sues', exact: false }).allTextContents()).toEqual(['issues 123']); + expect.soft(await screen.getByRole('link', { name: ' he \n llo ', exact: false }).allTextContents()).toEqual(['he llo 56']); + expect.soft(await screen.getByRole('button', { name: 'issues', exact: false }).allTextContents()).toEqual([]); + + expect.soft(await screen.getByRole('link', { name: 'sues' }).allTextContents()).toEqual([]); + expect.soft(await screen.getByRole('link', { name: ' he \n llo 56 ' }).allTextContents()).toEqual(['he llo 56']); + + expect.soft(await screen.getByRole('button', { name: 'Click me' }).allTextContents()).toEqual(['Click me']); + expect.soft(await screen.getByRole('button', { name: 'Click \\me' }).allTextContents()).toEqual([]); + expect.soft(await screen.getByRole('button', { name: 'Click \\\\me' }).allTextContents()).toEqual([]); + }); + + test('getByRole should accept regexp with v flag', async ({ screen, browser }) => { + await browser.goto(content(``)); + await expect(screen.getByRole('button', { name: new RegExp('Click me', 'v') })).toHaveCount(1); + await expect(screen.getByRole('button', { name: new RegExp('click me', 'iv') })).toHaveCount(1); + await expect(screen.getByRole('button', { name: new RegExp('Missing', 'v') })).toHaveCount(0, { timeout: 1000 }); + }); + + test('locators should not be affected by global and sticky regex flags', async ({ screen, browser }) => { + await browser.goto(content(` +
foo
foo
foo
+ + + + `)); + await expect(screen.getByText(/foo/)).toHaveCount(9); + await expect(screen.getByText(/foo/g)).toHaveCount(9); + await expect(screen.getByText(/foo/y)).toHaveCount(9); + await expect(screen.getByLabel(/foo/)).toHaveCount(3); + await expect(screen.getByLabel(/foo/g)).toHaveCount(3); + await expect(screen.getByLabel(/foo/y)).toHaveCount(3); + await expect(screen.getByRole('button', { name: /foo/ })).toHaveCount(3); + await expect(screen.getByRole('button', { name: /foo/g })).toHaveCount(3); + await expect(screen.getByRole('button', { name: /foo/y })).toHaveCount(3); + await expect(screen.getByPlaceholder(/foo/)).toHaveCount(3); + await expect(screen.getByPlaceholder(/foo/g)).toHaveCount(3); + await expect(screen.getByPlaceholder(/foo/y)).toHaveCount(3); + }); +}); diff --git a/apps/testbed/tests/selectors-role.e2e.ts b/apps/testbed/tests/selectors-role.e2e.ts new file mode 100644 index 0000000000..575969d096 --- /dev/null +++ b/apps/testbed/tests/selectors-role.e2e.ts @@ -0,0 +1,325 @@ +/** + * Adapted from microsoft/playwright tests/page/selectors-role.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: a `role=` selector is `getByRole` + * with the same options, a string name is exact by default so Playwright's + * default substring match is `{ exact: false }`, and an + * `evaluateAll(e => e.outerHTML)` read is the matches' texts or attributes. + * The `include-hidden`, `checked="mixed"`, and `pressed="mixed"` cases are + * left out: e2e getByRole has no includeHidden or mixed state. + * + * Not ported: + * - errors: Playwright `role=` selector parse errors. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import type { Locator } from 'e2e'; +import { content } from './helpers.ts'; + +/** The `aria-label` of every current match, in document order. */ +async function labels(locator: Locator): Promise<(string | null)[]> { + return Promise.all((await locator.all()).map((match) => match.getAttribute('aria-label'))); +} + +test.describe('selectors role', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should detect roles', async ({ screen, browser }) => { + await browser.goto(content(` + + + +

Heading

+
Hello
+
I am a dialog
+ `)); + expect(await screen.getByRole('button').allTextContents()).toEqual(['Hello']); + await expect(screen.getByRole('listbox')).toHaveCount(1); + await expect(screen.getByRole('listbox')).toHaveAttribute('multiple', ''); + await expect(screen.getByRole('combobox')).toHaveCount(1); + expect(await screen.getByRole('combobox').getAttribute('multiple')).toBe(null); + expect(await screen.getByRole('heading').allTextContents()).toEqual(['Heading']); + expect(await screen.getByRole('group').allTextContents()).toEqual(['Hello']); + expect(await screen.getByRole('dialog').allTextContents()).toEqual(['I am a dialog']); + expect(await screen.getByRole('menuitem').allTextContents()).toEqual([]); + }); + + test('should support selected', async ({ screen, browser }) => { + await browser.goto(content(` + +
+
Hi
+
Hello
+
+ `)); + expect(await screen.getByRole('option', { selected: true }).allTextContents()).toEqual(['Hello', 'Hi']); + expect(await screen.getByRole('option', { selected: false }).allTextContents()).toEqual(['Hi', 'Hello']); + }); + + test('should support checked', async ({ screen, browser }) => { + await browser.goto(content(` + + + +
Hi
+
Hello
+
Unknown
+ `)); + await browser.evaluate("() => { document.querySelector('[indeterminate]').indeterminate = true; }"); + + const checked = screen.getByRole('checkbox', { checked: true }); + await expect(checked).toHaveCount(2); + await expect(checked.first()).toHaveAttribute('checked', ''); + await expect(checked.nth(1)).toHaveText('Hi'); + + const unchecked = screen.getByRole('checkbox', { checked: false }); + await expect(unchecked).toHaveCount(3); + expect(await unchecked.first().getAttribute('checked')).toBe(null); + expect(await unchecked.first().getAttribute('indeterminate')).toBe(null); + expect(await unchecked.allTextContents()).toEqual(['', 'Hello', 'Unknown']); + + await expect(screen.getByRole('checkbox')).toHaveCount(6); + }); + + test('should support pressed', async ({ screen, browser }) => { + await browser.goto(content(` + + + + + `)); + expect(await screen.getByRole('button', { pressed: true }).allTextContents()).toEqual(['Hello']); + expect(await screen.getByRole('button', { pressed: false }).allTextContents()).toEqual(['Hi', 'Bye']); + expect(await screen.getByRole('button').allTextContents()).toEqual(['Hi', 'Hello', 'Bye', 'Mixed']); + }); + + test('should support expanded', async ({ screen, browser }) => { + await browser.goto(content(` +
Hi
+
Hello
+ + `)); + + expect(await screen.getByRole('treeitem').allTextContents()).toEqual(['Hi', 'Hello', 'Bye']); + expect(await screen.getByRole('treeitem', { expanded: true }).allTextContents()).toEqual(['Hello']); + expect(await screen.getByRole('treeitem', { expanded: false }).allTextContents()).toEqual(['Bye']); + expect(await browser.locator('[role=treeitem]:not([aria-expanded])').allTextContents()).toEqual(['Hi']); + }); + + test('should support disabled', async ({ screen, browser }) => { + await browser.goto(content(` + + + + +
+ +
+ + `)); + expect(await screen.getByRole('button', { disabled: true }).allTextContents()).toEqual(['Bye', 'Hello', 'Yay']); + expect(await screen.getByRole('button', { disabled: false }).allTextContents()).toEqual(['Hi', 'Oh']); + expect(await screen.getByRole('option', { disabled: true }).allTextContents()).toEqual(['one', 'three']); + expect(await screen.getByRole('option', { disabled: false }).allTextContents()).toEqual(['two']); + expect(await screen.getByRole('option').allTextContents()).toEqual(['one', 'two', 'three']); + }); + + test('should inherit disabled from the ancestor', async ({ browser }) => { + await browser.goto(content(` + + + + `)); + await expect(browser.locator('button')).toBeDisabled(); + + await browser.goto(content(` + +

Heading

+
+ `)); + await expect(browser.locator('h1')).not.toBeDisabled(); + }); + + test('should support disabled fieldset', async ({ screen, browser }) => { + await browser.goto(content(` +
+ + + + + +
+ +
+ +
+ +
+
+
+ +
+
+ + + + + + +
+ +
+
+ +
+
+ `)); + + await expect.soft(screen.getByTestId('inside-legend-element')).toBeEnabled(); + await expect.soft(screen.getByTestId('nested-inside-legend-element')).toBeEnabled(); + await expect.soft(screen.getByTestId('first-legend-element')).toBeEnabled(); + await expect.soft(screen.getByTestId('second-legend-element')).toBeDisabled(); + await expect.soft(screen.getByTestId('deep-button')).toBeDisabled(); + }); + + test('should support level', async ({ screen, browser }) => { + await browser.goto(content(` +

Hello

+

Hi

+
Bye
+ `)); + expect(await screen.getByRole('heading', { level: 1 }).allTextContents()).toEqual(['Hello']); + expect(await screen.getByRole('heading', { level: 3 }).allTextContents()).toEqual(['Hi']); + expect(await screen.getByRole('heading', { level: 5 }).allTextContents()).toEqual(['Bye']); + }); + + test('should filter hidden, unless explicitly asked for', async ({ screen, browser }) => { + await browser.goto(content(` + + + + + +
+ +
+
+ +
+ +
+ + + +
+ Open form + +
+ + + + + `)); + expect(await screen.getByRole('button').allTextContents()).toEqual(['Hi', 'Nay', 'Still here', 'Shadow1']); + await expect(screen.getByRole('textbox')).toHaveCount(1); + await expect(screen.getByRole('textbox')).toHaveAttribute('name', 'one'); + expect(await screen.getByRole('option').allTextContents()).toEqual(['One', 'Three']); + }); + + test('should support name', async ({ screen, browser }) => { + await browser.goto(content(` +
+
+ + + + `)); + expect(await labels(screen.getByRole('button', { name: 'Hello' }))).toEqual([' Hello ']); + expect(await labels(screen.getByRole('button', { name: ' \n Hello ' }))).toEqual([' Hello ']); + expect(await labels(screen.getByRole('button', { name: 'Hello', exact: false }))).toEqual([' Hello ']); + expect(await labels(screen.getByRole('button', { name: 'all', exact: false }))).toEqual(['Hallo']); + expect(await labels(screen.getByRole('button', { name: /^H[ae]llo$/ }))).toEqual([' Hello ', 'Hallo']); + expect(await labels(screen.getByRole('button', { name: /h.*o/i }))).toEqual([' Hello ', 'Hallo']); + }); + + test('should support option name with html whitespace', async ({ screen, browser }) => { + await browser.goto(content(` + + `)); + await expect(screen.getByRole('option', { name: 'HTML', exact: false })).toHaveCount(1); + }); + + test('hidden with shadow dom slots', async ({ screen, browser }) => { + await browser.goto(content(` +
+ +
+
+ +
+
+ +
+
+ +
+ + `)); + expect(await screen.getByRole('button').allTextContents()).toEqual(['visible1', 'visible2']); + }); + + test('should support output accessible name', async ({ screen, browser }) => { + await browser.goto(content(``)); + await expect(screen.getByRole('status', { name: 'Output1', exact: false })).toBeVisible(); + }); + + test('should not match scope by default', async ({ screen, browser }) => { + await browser.goto(content(` +
    +
  • + Parent list +
      +
    • child 1
    • +
    • child 2
    • +
    +
  • +
+ `)); + const children = screen.getByRole('listitem', { name: 'Parent list', exact: false }).getByRole('listitem'); + await expect(children).toHaveCount(2); + await expect(children).toHaveText(['child 1', 'child 2']); + }); +}); diff --git a/apps/testbed/tests/selectors-text.e2e.ts b/apps/testbed/tests/selectors-text.e2e.ts new file mode 100644 index 0000000000..0d33156ddb --- /dev/null +++ b/apps/testbed/tests/selectors-text.e2e.ts @@ -0,0 +1,64 @@ +/** + * Adapted from microsoft/playwright tests/page/selectors-text.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `locator(css, { hasText })` is a + * locator `filter({ hasText })`, `toHaveId(id)` an `id` attribute match. + * + * Not ported: + * - should work @smoke: Playwright `text=` and quoted selector strings, `page.$eval`. + * - should work with :text: Playwright `:text`, `:text-is`, `:text-matches` pseudo-classes. + * - should support empty string: same, plus `>>` chains. + * - should work across nodes: same, plus `text=`. + * - should work with text nodes in quoted mode: `text=` selectors. + * - should clear caches: element handles and `text=` selectors. + * - should work with :has-text: Playwright `:has-text` pseudo-class. + * - should work with large DOM: a timing run of Playwright selector engines. + * - should be case sensitive if quotes are specified: `text=` selectors. + * - should search for a substring without quotes: `text=` selectors. + * - should skip head, script and style: element handles and `text=` selectors. + * - should match input[type=button|submit|reset]: `text=` selectors. + * - should work for open shadow roots: `text=`, `text:light=` and `>>` selectors. + * - should prioritize light dom over shadow dom in the same parent: `>>` chain. + * - should waitForSelector with distributed elements: `page.waitForSelector` with a `>>` chain. + * - should match root after >>: `>>` chains. + * - should match root after >> with *: `>>` chain with a capture. + * - should work with leading and trailing spaces: `text=` selectors. + * - should work with unpaired quotes when not at the start: `text=` and `>>` selectors. + * - should work with paired quotes in the middle of selector: `>>` chains. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content } from './helpers.ts'; + +test.describe('selectors text', { requires: ['browser'], tags: ['playwright'] }, () => { + test('text-is() should ignore comments', async ({ screen, browser }) => { + await browser.goto(content(`
hello + + world
`)); + expect(await browser.locator('div').filter({ hasText: 'hello world' }).getAttribute('id')).toBe('me'); + expect(await screen.getByText('hello world').getAttribute('id')).toBe('me'); + }); + + test('hasText and internal:text should match full node text in strict mode', async ({ screen, browser }) => { + await browser.goto(content(` +
helloworld
+
hello
+ `)); + await expect(screen.getByText('helloworld')).toHaveAttribute('id', 'div1'); + await expect(screen.getByText('hello')).toHaveAttribute('id', 'div2'); + await expect(browser.locator('div').filter({ hasText: /^helloworld$/ })).toHaveAttribute('id', 'div1'); + await expect(browser.locator('div').filter({ hasText: /^hello$/ })).toHaveAttribute('id', 'div2'); + + await browser.goto(content(` +
helloworld
+
hello
+ `)); + await expect(screen.getByText('helloworld')).toHaveAttribute('id', 'div1'); + expect(await screen.getByText('hello').nth(0).getAttribute('id')).toBe('span1'); + expect(await screen.getByText('hello').nth(1).getAttribute('id')).toBe('span2'); + await expect(screen.getByText('hello')).toHaveCount(2); + await expect(browser.locator('div').filter({ hasText: /^helloworld$/ })).toHaveAttribute('id', 'div1'); + await expect(browser.locator('div').filter({ hasText: /^hello$/ })).toHaveAttribute('id', 'div2'); + }); +}); diff --git a/apps/testbed/tests/set-input-files.e2e.ts b/apps/testbed/tests/set-input-files.e2e.ts new file mode 100644 index 0000000000..6a679cc550 --- /dev/null +++ b/apps/testbed/tests/set-input-files.e2e.ts @@ -0,0 +1,287 @@ +/** + * Adapted from microsoft/playwright tests/page/page-set-input-files.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `setInputFiles` is the locator's, its paths resolve from the project + * root, and what the server received is what `/upload` answers with. + */ + +/* + * Not ported: + * - should set from memory: `setInputFiles` takes file paths, not `{ name, mimeType, buffer }` payloads. + * - input event.composed should be true and cross shadow dom boundary: sets a `{ name, mimeType, buffer }` payload, whose events Playwright dispatches itself. + */ + +import { test, type Browser } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { asset, content, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +type UploadedFile = { name: string; filename?: string; mimetype?: string; size: number; base64?: string }; + +/** Reads the first file of the input `selector` matches as text, in the page. */ +const readFirstFile = (selector: string): string => `() => { + const reader = new FileReader(); + const promise = new Promise((fulfill) => { reader.onload = fulfill; }); + reader.readAsText(document.querySelector(${JSON.stringify(selector)}).files[0]); + return promise.then(() => reader.result); +}`; + +const outputDirs: string[] = []; + +/** A fresh directory for files a test writes, removed after the test. */ +function outputDir(): string { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'e2e-upload-')); + outputDirs.push(dir); + return dir; +} + +/** Writes a 200MB file of `A`s, Playwright's large upload. */ +async function writeLargeFile(file: string): Promise { + const str = 'A'.repeat(4 * 1024); + const stream = fs.createWriteStream(file); + for (let i = 0; i < 50 * 1024; i++) { + await new Promise((fulfill, reject) => stream.write(str, (error) => (error ? reject(error) : fulfill()))); + } + await new Promise((fulfill) => stream.end(fulfill)); +} + +/** The files the server parsed from the form the page posted to `/upload`. */ +async function uploaded(browser: Browser): Promise { + return JSON.parse(await browser.evaluate('document.body.textContent')) as UploadedFile[]; +} + +/** Records the input and change events the input `selector` matches dispatches, into `window.events`. */ +const recordEvents = (selector: string): string => `() => { + window.events = []; + const e = document.querySelector(${JSON.stringify(selector)}); + e.addEventListener('input', () => window.events.push('input')); + e.addEventListener('change', () => window.events.push('change')); +}`; + +test.describe('page set input files', { requires: ['browser'], tags: ['playwright'] }, () => { + test.afterEach(() => { + for (const dir of outputDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); + }); + + test('should upload the file', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + await browser.locator('input[type=file]').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + expect(await browser.evaluate(readFirstFile('input'))).toBe('contents of the file'); + }); + + test('should upload a folder', async ({ browser }) => { + await browser.goto('/input/folderupload.html'); + const dir = path.join(outputDir(), 'file-upload-test'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'file1.txt'), 'file1 content'); + fs.writeFileSync(path.join(dir, 'file2'), 'file2 content'); + fs.mkdirSync(path.join(dir, 'sub-dir')); + fs.writeFileSync(path.join(dir, 'sub-dir', 'really.txt'), 'sub-dir file content'); + await browser.locator('input[type=file]').setInputFiles(dir); + const webkitRelativePaths = await browser.evaluate("() => [...document.querySelector('input').files].map((f) => f.webkitRelativePath)"); + expect(new Set(webkitRelativePaths)).toEqual(new Set([ + 'file-upload-test/sub-dir/really.txt', + 'file-upload-test/file1.txt', + 'file-upload-test/file2', + ])); + for (let i = 0; i < webkitRelativePaths.length; i++) { + const fileContent = await browser.evaluate(`(i) => { + const reader = new FileReader(); + const promise = new Promise((fulfill) => { reader.onload = fulfill; }); + reader.readAsText(document.querySelector('input').files[i]); + return promise.then(() => reader.result); + }`, i); + expect(fileContent).toEqual(fs.readFileSync(path.join(dir, '..', webkitRelativePaths[i]!)).toString()); + } + }); + + test('should upload a folder and throw for multiple directories', async ({ browser }) => { + await browser.goto('/input/folderupload.html'); + const dir = path.join(outputDir(), 'file-upload-test'); + fs.mkdirSync(path.join(dir, 'folder1'), { recursive: true }); + fs.writeFileSync(path.join(dir, 'folder1', 'file1.txt'), 'file1 content'); + fs.mkdirSync(path.join(dir, 'folder2'), { recursive: true }); + fs.writeFileSync(path.join(dir, 'folder2', 'file2.txt'), 'file2 content'); + const error = await browser.locator('input[type=file]').setInputFiles([path.join(dir, 'folder1'), path.join(dir, 'folder2')]).catch((caught: Error) => caught); + expect((error as Error).message).toContain('Multiple directories are not supported'); + }); + + test('should throw if a directory and files are passed', async ({ browser }) => { + await browser.goto('/input/folderupload.html'); + const dir = path.join(outputDir(), 'file-upload-test'); + fs.mkdirSync(path.join(dir, 'folder1'), { recursive: true }); + fs.writeFileSync(path.join(dir, 'folder1', 'file1.txt'), 'file1 content'); + const error = await browser.locator('input[type=file]').setInputFiles([path.join(dir, 'folder1'), path.join(dir, 'folder1', 'file1.txt')]).catch((caught: Error) => caught); + expect((error as Error).message).toContain('File paths must be all files or a single directory'); + }); + + test('should throw when uploading a folder in a normal file upload input', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + const dir = path.join(outputDir(), 'file-upload-test'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'file1.txt'), 'file1 content'); + const error = await browser.locator('input[type=file]').setInputFiles(dir).catch((caught: Error) => caught); + expect((error as Error).message).toContain('File input does not support directories, pass individual files instead'); + }); + + test('should throw when uploading a file in a directory upload input', async ({ browser }) => { + await browser.goto('/input/folderupload.html'); + const error = await browser.locator('input[type=file]').setInputFiles(asset('file to upload.txt')).catch((caught: Error) => caught); + expect((error as Error).message).toContain('[webkitdirectory] input requires passing a path to a directory'); + }); + + test('should upload a file after popup', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + await browser.evaluate("() => { window['__popup'] = window.open('about:blank'); }"); + await browser.evaluate("() => { window['__popup'].close(); }"); + await browser.locator('input[type=file]').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + }); + + test('should upload large file', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + const uploadFile = path.join(outputDir(), '200MB.zip'); + await writeLargeFile(uploadFile); + await browser.evaluate(recordEvents('input[type="file"]')); + await browser.locator('input[type="file"]').setInputFiles(uploadFile); + expect(await browser.evaluate("() => document.querySelector('input[type=\"file\"]').files[0].name")).toBe('200MB.zip'); + expect(await browser.evaluate('() => window.events')).toEqual(['input', 'change']); + await Promise.all([ + browser.waitForURL('/upload'), + browser.locator('input[type=submit]').tap(), + ]); + const [file1] = await uploaded(browser); + expect(file1!.filename).toBe('200MB.zip'); + expect(file1!.size).toBe(200 * 1024 * 1024); + fs.unlinkSync(uploadFile); + }); + + test('should throw an error if the file does not exist', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + const error = await browser.locator('input[type=file]').setInputFiles('i actually do not exist.txt').catch((caught: Error) => caught); + expect((error as Error).message).toContain('ENOENT: no such file or directory'); + expect((error as Error).message).toContain('i actually do not exist.txt'); + }); + + test('should upload large file with relative path', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + const uploadFile = path.join(outputDir(), '200MB.zip'); + await writeLargeFile(uploadFile); + await browser.evaluate(recordEvents('input[type="file"]')); + const relativeUploadPath = path.relative(process.cwd(), uploadFile); + expect(path.isAbsolute(relativeUploadPath)).toBeFalsy(); + await browser.locator('input[type="file"]').setInputFiles(relativeUploadPath); + expect(await browser.evaluate("() => document.querySelector('input[type=\"file\"]').files[0].name")).toBe('200MB.zip'); + expect(await browser.evaluate('() => window.events')).toEqual(['input', 'change']); + await Promise.all([ + browser.waitForURL('/upload'), + browser.locator('input[type=submit]').tap(), + ]); + const [file1] = await uploaded(browser); + expect(file1!.filename).toBe('200MB.zip'); + expect(file1!.size).toBe(200 * 1024 * 1024); + fs.unlinkSync(uploadFile); + }); + + test('should upload the file with spaces in name', async ({ browser }) => { + await browser.goto('/input/fileupload.html'); + await browser.locator('input[type=file]').setInputFiles(asset('file to upload.txt')); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file to upload.txt'); + expect(await browser.evaluate(readFirstFile('input'))).toBe('contents of the file'); + }); + + test('should work @smoke', async ({ browser }) => { + await browser.goto(content('')); + await browser.locator('input[type=file]').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate("() => document.querySelector('input').files.length")).toBe(1); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + }); + + test('should work with CSP', async ({ browser }) => { + await browser.goto(`/respond?headers=${encodeURIComponent(JSON.stringify({ 'content-type': 'text/html', 'content-security-policy': 'default-src "none"' }))}&body=${encodeURIComponent('')}`); + await browser.locator('input[type=file]').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate("() => document.querySelector('input').files.length")).toBe(1); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + }); + + test('should detect mime type', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` +
+ + + +
`)); + await browser.locator('input[name=file1]').setInputFiles(asset('file-to-upload.txt')); + await browser.locator('input[name=file2]').setInputFiles(asset('pptr.png')); + await Promise.all([ + browser.waitForURL('/upload'), + browser.locator('input[type=submit]').tap(), + ]); + const [file1, file2] = await uploaded(browser); + expect(file1!.filename).toBe('file-to-upload.txt'); + expect(file1!.mimetype).toBe('text/plain'); + expect(Buffer.from(file1!.base64!, 'base64').toString()).toBe(fs.readFileSync(asset('file-to-upload.txt')).toString()); + expect(file2!.filename).toBe('pptr.png'); + expect(file2!.mimetype).toBe('image/png'); + expect(Buffer.from(file2!.base64!, 'base64').toString()).toBe(fs.readFileSync(asset('pptr.png')).toString()); + }); + + test('should not trim big uploaded files', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const DATA_SIZE = Math.pow(2, 20); + const files = await browser.evaluate(`async (size) => { + const body = new FormData(); + body.set('file', new Blob([new Uint8Array(size)])); + return (await fetch('/upload', { method: 'POST', body })).json(); + }`, DATA_SIZE); + expect(files[0]!.size).toBe(DATA_SIZE); + }); + + test('should emit input and change events', async ({ browser }) => { + await browser.goto(content(` + + `)); + await browser.locator('input[type=file]').setInputFiles(asset('file-to-upload.txt')); + const events = await browser.evaluate<{ type: string }[]>('() => window.events'); + expect(events.length).toBe(2); + expect(events[0]!.type).toBe('input'); + expect(events[1]!.type).toBe('change'); + }); + + test('input should trigger events when files changed second time', async ({ browser }) => { + await browser.goto(content('')); + await browser.evaluate(recordEvents('input')); + + await browser.locator('input[type=file]').setInputFiles(asset('file-to-upload.txt')); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('file-to-upload.txt'); + expect(await browser.evaluate('() => window.events')).toEqual(['input', 'change']); + + await browser.evaluate('() => { window.events.length = 0; }'); + + await browser.locator('input[type=file]').setInputFiles(asset('pptr.png')); + expect(await browser.evaluate("() => document.querySelector('input').files[0].name")).toBe('pptr.png'); + expect(await browser.evaluate('() => window.events')).toEqual(['input', 'change']); + }); + + test('should preserve lastModified timestamp', async ({ browser }) => { + await browser.goto(content('')); + const files = ['file-to-upload.txt', 'file-to-upload-2.txt']; + await browser.locator('input[type=file]').setInputFiles(files.map(asset)); + expect(await browser.evaluate("() => [...document.querySelector('input').files].map((f) => f.name)")).toEqual(files); + const timestamps = await browser.evaluate("() => [...document.querySelector('input').files].map((f) => f.lastModified)"); + const expectedTimestamps = files.map((file) => Math.round(fs.statSync(asset(file)).mtimeMs)); + for (let i = 0; i < timestamps.length; i++) { + expect(Math.abs(timestamps[i]! - expectedTimestamps[i]!)).toBeLessThanOrEqual(1000); + } + }); +}); diff --git a/apps/testbed/tests/wait-for-navigation.e2e.ts b/apps/testbed/tests/wait-for-navigation.e2e.ts new file mode 100644 index 0000000000..7a52056489 --- /dev/null +++ b/apps/testbed/tests/wait-for-navigation.e2e.ts @@ -0,0 +1,168 @@ +/** + * Adapted from microsoft/playwright tests/page/page-wait-for-navigation.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `page.waitForNavigation()` is `browser.waitForURL` with the URL the + * navigation lands on, and a `url` matcher is a RegExp. + */ + +/* + * Not ported: + * - should work with both domcontentloaded and load: needs `waitForNavigation({ waitUntil })`. + * - should work with commit: needs `waitForNavigation({ waitUntil: 'commit' })`. + * - should work with clicking on links which do not commit navigation: needs an HTTPS server with a bad certificate. + * - should work when subframe issues window.stop(): needs `frameattached` and `framenavigated` events. + * - should work on frame: needs `frame.waitForNavigation`. + * - should fail when frame detaches: needs `frame.waitForNavigation`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, CROSS, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +test.describe('page wait for navigation', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should work', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await Promise.all([ + browser.waitForURL('/grid.html'), + browser.evaluate('(url) => { window.location.href = url; }', `${PREFIX}/grid.html`), + ]); + expect(await browser.url()).toContain('grid.html'); + }); + + test('should respect timeout', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto('/one-style.html'); + const promise = browser.waitForURL('/frame.html', { timeout: 5000 }); + await browser.goto(EMPTY_PAGE); + const error = await promise.catch((caught: Error) => caught); + expect((error as Error).message).toContain('/frame.html'); + expect((error as Error).message).toContain(EMPTY_PAGE); + }); + + test('should work with clicking on anchor links', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const page = content("foobar"); + await browser.goto(page); + await Promise.all([ + browser.waitForURL(`${page}#foobar`), + browser.locator('a').tap(), + ]); + expect(await browser.url()).toBe(`${PREFIX}${page}#foobar`); + }); + + test('should work with history.pushState()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + SPA + + `)); + await Promise.all([ + browser.waitForURL('/wow.html'), + browser.locator('a').tap(), + ]); + expect(await browser.url()).toBe(`${PREFIX}/wow.html`); + }); + + test('should work with history.replaceState()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + SPA + + `)); + await Promise.all([ + browser.waitForURL('/replaced.html'), + browser.locator('a').tap(), + ]); + expect(await browser.url()).toBe(`${PREFIX}/replaced.html`); + }); + + test('should work with DOM history.back()/history.forward()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + back + forward + + `)); + expect(await browser.url()).toBe(`${PREFIX}/second.html`); + await Promise.all([ + browser.waitForURL('/first.html'), + browser.locator('a#back').tap(), + ]); + expect(await browser.url()).toBe(`${PREFIX}/first.html`); + await Promise.all([ + browser.waitForURL('/second.html'), + browser.locator('a#forward').tap(), + ]); + expect(await browser.url()).toBe(`${PREFIX}/second.html`); + }); + + test('should work with url match', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto(content('

blank

')); + let response1 = false; + const response1Promise = browser.waitForURL(/one-style\.html/).then(() => (response1 = true)); + let response2 = false; + const response2Promise = browser.waitForURL(/\/frame.html/).then(() => (response2 = true)); + let response3 = false; + const response3Promise = browser.waitForURL(/[?&]foo=bar/).then(() => (response3 = true)); + expect(response1).toBe(false); + expect(response2).toBe(false); + expect(response3).toBe(false); + await browser.goto(EMPTY_PAGE); + expect(response1).toBe(false); + expect(response2).toBe(false); + expect(response3).toBe(false); + await browser.goto('/frame.html'); + expect(response1).toBe(false); + await response2Promise; + expect(response2).toBe(true); + expect(response3).toBe(false); + await browser.goto('/one-style.html'); + await response1Promise; + expect(response1).toBe(true); + expect(response2).toBe(true); + expect(response3).toBe(false); + await browser.goto('/frame.html?foo=bar'); + await response3Promise; + expect(response1).toBe(true); + expect(response2).toBe(true); + expect(response3).toBe(true); + await browser.goto('/empty.html'); + }); + + test('should work with url match for same document navigations', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + let resolved = false; + const waitPromise = browser.waitForURL(/third\.html/).then(() => (resolved = true)); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/first.html'); }"); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/second.html'); }"); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/third.html'); }"); + await waitPromise; + expect(resolved).toBe(true); + }); + + test('should work for cross-process navigations', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const url = `${CROSS}/empty.html`; + const waitPromise = browser.waitForURL(url); + const gotoPromise = browser.goto(url, { waitUntil: 'domcontentloaded' }); + await waitPromise; + expect(await browser.url()).toBe(url); + expect(await browser.evaluate('document.location.href')).toBe(url); + await gotoPromise; + }); +}); diff --git a/apps/testbed/tests/wait-for-response.e2e.ts b/apps/testbed/tests/wait-for-response.e2e.ts new file mode 100644 index 0000000000..f8c8eaaa9f --- /dev/null +++ b/apps/testbed/tests/wait-for-response.e2e.ts @@ -0,0 +1,56 @@ +/** + * Adapted from microsoft/playwright tests/page/page-wait-for-response.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `browser.waitForResponse` takes a URL pattern. + */ + +/* + * Not ported: + * - should respect timeout: needs `page.waitForEvent('response')`. + * - should respect default timeout: needs `page.setDefaultTimeout` and a predicate. + * - should work with predicate: needs `page.waitForEvent('response', predicate)`. + * - should work with async predicate: needs response predicates. + * - sync predicate should be only called once: needs response predicates. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +test.describe('page wait for response', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should work', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const [response] = await Promise.all([ + browser.waitForResponse(`${PREFIX}/digits/2.png`), + browser.evaluate(`() => { + void fetch('/digits/1.png'); + void fetch('/digits/2.png'); + void fetch('/digits/3.png'); + }`), + ]); + expect(response.url).toBe(`${PREFIX}/digits/2.png`); + }); + + test('should log the url', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const error1 = await browser.waitForResponse('foo.css', { timeout: 1000 }).catch((caught: Error) => caught); + expect((error1 as Error).message).toContain('"foo.css"'); + const error2 = await browser.waitForResponse(/foo.css/i, { timeout: 1000 }).catch((caught: Error) => caught); + expect((error2 as Error).message).toContain('/foo.css/i'); + }); + + test('should work with no timeout', { skip: 'a timeout must be positive, so there is no `timeout: 0` for no timeout (refused as INVALID_ARGUMENT, which `fail` does not cover)' }, async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + const [response] = await Promise.all([ + browser.waitForResponse(`${PREFIX}/digits/2.png`, { timeout: 0 }), + browser.evaluate(`() => setTimeout(() => { + void fetch('/digits/1.png'); + void fetch('/digits/2.png'); + void fetch('/digits/3.png'); + }, 50) && null`), + ]); + expect(response.url).toBe(`${PREFIX}/digits/2.png`); + }); +}); diff --git a/apps/testbed/tests/wait-for-url.e2e.ts b/apps/testbed/tests/wait-for-url.e2e.ts new file mode 100644 index 0000000000..8b2ef08630 --- /dev/null +++ b/apps/testbed/tests/wait-for-url.e2e.ts @@ -0,0 +1,106 @@ +/** + * Adapted from microsoft/playwright tests/page/page-wait-for-url.spec.ts at v1.64.1. + * Copyright Microsoft Corporation. Licensed under the Apache License 2.0 (see ../app/playwright/LICENSE). + * Rewritten against the e2e public API: `waitForURL` takes a URL or a RegExp, so a glob is the URL it names. + */ + +/* + * Not ported: + * - should work with both domcontentloaded and load: needs `waitForURL({ waitUntil })`. + * - should work with commit: needs `waitForURL({ waitUntil })`. + * - should work with commit and about:blank: needs `waitForURL({ waitUntil })`. + * - should work on frame: needs `frame.waitForURL`. + */ + +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; +import { content, PREFIX } from './helpers.ts'; + +const EMPTY_PAGE = `${PREFIX}/empty.html`; + +test.describe('page wait for url', { requires: ['browser'], tags: ['playwright'] }, () => { + test('should work', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.evaluate('(url) => { window.location.href = url; }', `${PREFIX}/grid.html`); + await browser.waitForURL('/grid.html'); + }); + + test('should respect timeout', async ({ browser }) => { + // e2e opens no page before the first goto, where Playwright starts on about:blank. + await browser.goto(EMPTY_PAGE); + const promise = browser.waitForURL('/frame.html', { timeout: 2500 }).catch((caught: Error) => caught); + await browser.goto(EMPTY_PAGE); + const error = await promise; + expect((error as Error).message).toContain('frame.html'); + }); + + test('should work with clicking on anchor links', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content("foobar")); + await browser.locator('a').tap(); + await browser.waitForURL(/#foobar$/); + }); + + test('should work with history.pushState()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + SPA + + `)); + await browser.locator('a').tap(); + await browser.waitForURL('/wow.html'); + expect(await browser.url()).toBe(`${PREFIX}/wow.html`); + }); + + test('should work with history.replaceState()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + SPA + + `)); + await browser.locator('a').tap(); + await browser.waitForURL('/replaced.html'); + expect(await browser.url()).toBe(`${PREFIX}/replaced.html`); + }); + + test('should work with DOM history.back()/history.forward()', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + await browser.goto(content(` + back + forward + + `)); + expect(await browser.url()).toBe(`${PREFIX}/second.html`); + + await browser.locator('a#back').tap(); + await browser.waitForURL('/first.html'); + expect(await browser.url()).toBe(`${PREFIX}/first.html`); + + await browser.locator('a#forward').tap(); + await browser.waitForURL('/second.html'); + expect(await browser.url()).toBe(`${PREFIX}/second.html`); + }); + + test('should work with url match for same document navigations', async ({ browser }) => { + await browser.goto(EMPTY_PAGE); + let resolved = false; + const waitPromise = browser.waitForURL(/third\.html/).then(() => (resolved = true)); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/first.html'); }"); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/second.html'); }"); + expect(resolved).toBe(false); + await browser.evaluate("() => { history.pushState({}, '', '/third.html'); }"); + await waitPromise; + expect(resolved).toBe(true); + }); +}); diff --git a/packages/e2e/src/run/fixture-recording.ts b/packages/e2e/src/run/fixture-recording.ts index 45d3f31f88..1557b680c2 100644 --- a/packages/e2e/src/run/fixture-recording.ts +++ b/packages/e2e/src/run/fixture-recording.ts @@ -75,7 +75,7 @@ export class FixtureRecorder { if (timeout !== false && timeout !== undefined && (!Number.isFinite(timeout) || timeout <= 0)) { throw new TestError('INVALID_ARGUMENT', `${api} timeout must be positive and finite`); } - const pending = withAbort(() => translated(api, body), environment.budget.signal, () => new TestError('CANCELLED', `${api} cancelled`)); + const pending = withAbort(() => translated(label === '' ? api : `${api} ${label}`, body), environment.budget.signal, () => new TestError('CANCELLED', `${api} cancelled`)); if (timeout === false) return pending; const timeoutMs = timeout ?? environment.config.actionTimeout; return withTimeout(pending, timeoutMs, () => new TestError('ACTION_FAILED', `${api} exceeded its timeout of ${timeoutMs}ms`)); @@ -87,13 +87,14 @@ export class FixtureRecorder { * Runs one operation and maps an `EngineError` it rejects with onto the runner * taxonomy, as every other engine surface is mapped: a contributed fixture * that lost its session throws `INVALID_STATE`, which a test reads as - * `APP_NOT_OPEN`. Anything else is rethrown as the fixture threw it. + * `APP_NOT_OPEN`. Anything else is rethrown as the fixture threw it. `call` + * names the operation and its label, so a timeout says what it waited for. */ -async function translated(api: string, body: () => Promise): Promise { +async function translated(call: string, body: () => Promise): Promise { try { return await body(); } catch (cause) { - throw asEngineError(cause) === undefined ? cause : translateEngineError(cause, ` in ${api}`); + throw asEngineError(cause) === undefined ? cause : translateEngineError(cause, ` in ${call}`); } } diff --git a/packages/e2e/tests/unit/fixture-runtime.test.ts b/packages/e2e/tests/unit/fixture-runtime.test.ts index 8a0efa0a35..617a84d654 100644 --- a/packages/e2e/tests/unit/fixture-runtime.test.ts +++ b/packages/e2e/tests/unit/fixture-runtime.test.ts @@ -299,15 +299,17 @@ describe('explicit fixture operations', () => { gadget: (context) => context.fixture('gadget', { async lost(): Promise { throw new EngineError('INVALID_STATE', 'appstate requires an active session', { retryable: false }); }, async slow(): Promise { throw new EngineError('OPERATION_TIMEOUT', 'appstate timed out', { retryable: false }); }, + async wait(_pattern: string): Promise { throw new EngineError('OPERATION_TIMEOUT', 'wait timed out', { retryable: false }); }, async denied(): Promise { throw new TestError('POLICY_DENIED', 'no'); }, async plain(): Promise { throw new Error('plain failure'); }, - }, { lost: { kind: 'resource' }, slow: { kind: 'resource' }, denied: { kind: 'resource' }, plain: { kind: 'resource' } }), + }, { lost: { kind: 'resource' }, slow: { kind: 'resource' }, wait: { kind: 'resource', label: (pattern) => JSON.stringify(pattern) }, denied: { kind: 'resource' }, plain: { kind: 'resource' } }), }, }); const { fixtures } = runtime(engine); - const gadget = (fixtures as unknown as { gadget: Record<'lost' | 'slow' | 'denied' | 'plain', () => Promise> }).gadget; + const gadget = (fixtures as unknown as { gadget: Record<'lost' | 'slow' | 'denied' | 'plain', () => Promise> & { wait(pattern: string): Promise } }).gadget; await expect(gadget.lost()).rejects.toMatchObject({ code: 'APP_NOT_OPEN', category: 'test', message: 'appstate requires an active session' }); await expect(gadget.slow()).rejects.toMatchObject({ code: 'ACTION_FAILED', message: 'operation timed out in gadget.slow' }); + await expect(gadget.wait('foo.css')).rejects.toMatchObject({ code: 'ACTION_FAILED', message: 'operation timed out in gadget.wait "foo.css"' }); await expect(gadget.denied()).rejects.toMatchObject({ code: 'POLICY_DENIED' }); await expect(gadget.plain()).rejects.toThrow('plain failure'); }); diff --git a/packages/web/src/browser.ts b/packages/web/src/browser.ts index 1983fe55d1..d1c8f67816 100644 --- a/packages/web/src/browser.ts +++ b/packages/web/src/browser.ts @@ -797,13 +797,13 @@ export function createBrowserFixture(surface: PlaywrightSurface, context: Engine forward: navigationCall, url: action, title: action, - waitForURL: { ...navigationCall, verifies: true, label: (url) => String(url) }, + waitForURL: { ...navigationCall, verifies: true, label: patternLabel }, evaluate: action, addInitScript: { ...action, label: (script) => initScriptLabel(script) }, - route: { ...action, label: (pattern) => String(pattern) }, - unroute: { ...action, label: (pattern) => String(pattern) }, + route: { ...action, label: patternLabel }, + unroute: { ...action, label: patternLabel }, unrouteAll: action, - waitForResponse: { ...action, timeout: (_pattern, options) => options?.timeout, label: (pattern) => String(pattern) }, + waitForResponse: { ...action, timeout: (_pattern, options) => options?.timeout, label: patternLabel }, cookies: action, setCookies: action, clearCookies: action, @@ -949,6 +949,11 @@ function requireSelector(method: string, selector: unknown): string { return selector; } +/** A URL pattern as steps and errors name it: a string quoted, a RegExp as its literal. */ +function patternLabel(pattern: string | RegExp): string { + return typeof pattern === 'string' ? JSON.stringify(pattern) : String(pattern); +} + /** * The scope for the innermost of `frames` (outermost first). Every query and * both escape hatches compile through the same `frame` chain, so a `locator` diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 87925fbc64..28fd25ef3a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -257,9 +257,15 @@ importers: '@types/node': specifier: 26.6.6 version: 26.6.6 + '@types/pngjs': + specifier: 6.0.5 + version: 6.0.5 ai: specifier: 7.0.162 version: 7.0.162(zod@4.6.7) + pngjs: + specifier: 7.0.0 + version: 7.0.0 typescript: specifier: 7.0.2 version: 7.0.2