Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork57
ImplementonPageLoad for playwright#464
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
4 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
156 changes: 156 additions & 0 deletionsPlugins/PackageToJS/Fixtures/PlaywrightOnPageLoadTest/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,156 @@ | ||
| #Playwright OnPageLoad Test | ||
| This example demonstrates how to expose JavaScript functions to your Swift/WebAssembly tests using Playwright's`page.exposeFunction` API. | ||
| ##How it works | ||
| 1.**Expose Script**: A JavaScript file that exports functions to be exposed in the browser context | ||
| 2.**Swift Tests**: Call these exposed functions using JavaScriptKit's`JSObject.global` API | ||
| 3.**Test Runner**: The`--playwright-expose` flag loads the script and exposes the functions before running tests | ||
| ##Usage | ||
| ###Define exposed functions in a JavaScript file | ||
| **Important:** All functions exposed via Playwright's`page.exposeFunction` are async from the browser's perspective, meaning they always return Promises. Define them as`async` for clarity. | ||
| ####Option 1: Function with Page Access (Recommended) | ||
| Export a function that receives the Playwright`page` object. This allows your exposed functions to interact with the browser page: | ||
| ```javascript | ||
| /** | ||
| *@param{import('playwright').Page}page - The Playwright Page object | ||
| */ | ||
| exportasyncfunctionexposedFunctions(page) { | ||
| return { | ||
| expectToBeTrue:async ()=> { | ||
| returntrue; | ||
| }, | ||
| // Use the page object to interact with the browser | ||
| getTitle:async ()=> { | ||
| returnawaitpage.title(); | ||
| }, | ||
| clickButton:async (selector)=> { | ||
| awaitpage.click(selector); | ||
| returntrue; | ||
| }, | ||
| evaluate:async (script)=> { | ||
| returnawaitpage.evaluate(script); | ||
| }, | ||
| screenshot:async ()=> { | ||
| constbuffer=awaitpage.screenshot(); | ||
| returnbuffer.toString('base64'); | ||
| } | ||
| }; | ||
| } | ||
| ``` | ||
| ####Option 2: Static Object (Simple Cases) | ||
| For simple functions that don't need page access: | ||
| ```javascript | ||
| exportconstexposedFunctions= { | ||
| expectToBeTrue:async ()=> { | ||
| returntrue; | ||
| }, | ||
| addNumbers:async (a,b)=> { | ||
| return a+ b; | ||
| } | ||
| }; | ||
| ``` | ||
| ###Use the functions in Swift tests | ||
| ```swift | ||
| importXCTest | ||
| importJavaScriptKit | ||
| importJavaScriptEventLoop | ||
| finalclassCheckTests:XCTestCase{ | ||
| functestExpectToBeTrue()asyncthrows { | ||
| guardlet expectToBeTrue= JSObject.global.expectToBeTrue.function | ||
| else {returnXCTFail("Function expectToBeTrue not found") } | ||
| // Functions exposed via Playwright return Promises | ||
| guardlet promiseObject=expectToBeTrue().object | ||
| else {returnXCTFail("expectToBeTrue() did not return an object") } | ||
| guardlet promise=JSPromise(promiseObject) | ||
| else {returnXCTFail("expectToBeTrue() did not return a Promise") } | ||
| let resultValue=tryawait promise.value | ||
| guardlet result= resultValue.boolean | ||
| else {returnXCTFail("expectToBeTrue() returned nil") } | ||
| XCTAssertTrue(result) | ||
| } | ||
| } | ||
| ``` | ||
| ###Run tests with the expose script | ||
| ```bash | ||
| swift package jstest --environment browser --playwright-expose path/to/expose.js | ||
| ``` | ||
| ###Backward Compatibility | ||
| You can also use`--prelude` to define exposed functions, which allows combining WASM setup options (`setupOptions`) and Playwright exposed functions in one file: | ||
| ```bash | ||
| swift package jstest --environment browser --prelude path/to/prelude.js | ||
| ``` | ||
| However, using`--playwright-expose` is recommended for clarity and separation of concerns. | ||
| ##Advanced Usage | ||
| ###Access to Page Context | ||
| When you export a function (as shown in Option 1), you receive the Playwright`page` object, which gives you full access to the browser page. This is powerful because you can: | ||
| -**Query the DOM**:`await page.$('selector')` | ||
| -**Execute JavaScript**:`await page.evaluate('...')` | ||
| -**Take screenshots**:`await page.screenshot()` | ||
| -**Navigate**:`await page.goto('...')` | ||
| -**Handle events**:`page.on('console', ...)` | ||
| ###Async Initialization | ||
| You can perform async initialization before returning your functions: | ||
| ```javascript | ||
| exportasyncfunctionexposedFunctions(page) { | ||
| // Perform async setup | ||
| constconfig=awaitloadConfiguration(); | ||
| // Navigate to a specific page if needed | ||
| awaitpage.goto('http://example.com'); | ||
| return { | ||
| expectToBeTrue:async ()=>true, | ||
| getConfig:async ()=> config, | ||
| // Function that uses both page and initialization data | ||
| checkElement:async (selector)=> { | ||
| constelement=awaitpage.$(selector); | ||
| return element!==null; | ||
| } | ||
| }; | ||
| } | ||
| ``` | ||
| ###Best Practices | ||
| 1.**Always use`async` functions**: All exposed functions are async from the browser's perspective | ||
| 2.**Capture`page` in closures**: Functions returned from`exposedFunctions(page)` can access`page` via closure | ||
| 3.**Handle errors**: Wrap page interactions in try-catch blocks | ||
| 4.**Return serializable data**: Functions can only return JSON-serializable values |
17 changes: 17 additions & 0 deletionsPlugins/PackageToJS/Fixtures/PlaywrightOnPageLoadTest/SwiftTesting/Package.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| // swift-tools-version: 6.0 | ||
| import PackageDescription | ||
| let package = Package( | ||
| name: "Check", | ||
| dependencies: [.package(name: "JavaScriptKit", path: "../../../../../")], | ||
| targets: [ | ||
| .testTarget( | ||
| name: "CheckTests", | ||
| dependencies: [ | ||
| "JavaScriptKit", | ||
| .product(name: "JavaScriptEventLoopTestSupport", package: "JavaScriptKit"), | ||
| ], | ||
| path: "Tests" | ||
| ) | ||
| ] | ||
| ) |
25 changes: 25 additions & 0 deletionsPlugins/PackageToJS/Fixtures/PlaywrightOnPageLoadTest/SwiftTesting/Tests/CheckTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import Testing | ||
| import JavaScriptKit | ||
| import JavaScriptEventLoop | ||
| @Test func expectToBeTrue() async throws { | ||
| let expectToBeTrue = try #require(JSObject.global.expectToBeTrue.function) | ||
| // expectToBeTrue returns a Promise, so we need to await it | ||
| let promiseObject = try #require(expectToBeTrue.callAsFunction().object) | ||
| let promise = try #require(JSPromise(promiseObject)) | ||
| let resultValue = try await promise.value | ||
| #expect(resultValue.boolean == true) | ||
| } | ||
| @Test func getTitleOfPage() async throws { | ||
| let getTitle = try #require(JSObject.global.getTitle.function) | ||
| // getTitle returns a Promise, so we need to await it | ||
| let promiseObject = try #require(getTitle.callAsFunction().object) | ||
| let promise = try #require(JSPromise(promiseObject)) | ||
| let resultValue = try await promise.value | ||
| #expect(resultValue.string == "") | ||
| } |
17 changes: 17 additions & 0 deletionsPlugins/PackageToJS/Fixtures/PlaywrightOnPageLoadTest/XCTest/Package.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| // swift-tools-version: 6.0 | ||
| import PackageDescription | ||
| let package = Package( | ||
| name: "Check", | ||
| dependencies: [.package(name: "JavaScriptKit", path: "../../../../../")], | ||
| targets: [ | ||
| .testTarget( | ||
| name: "CheckTests", | ||
| dependencies: [ | ||
| "JavaScriptKit", | ||
| .product(name: "JavaScriptEventLoopTestSupport", package: "JavaScriptKit"), | ||
| ], | ||
| path: "Tests" | ||
| ) | ||
| ] | ||
| ) |
41 changes: 41 additions & 0 deletionsPlugins/PackageToJS/Fixtures/PlaywrightOnPageLoadTest/XCTest/Tests/CheckTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import XCTest | ||
| import JavaScriptKit | ||
| import JavaScriptEventLoop | ||
| final class CheckTests: XCTestCase { | ||
| func testExpectToBeTrue() async throws { | ||
| guard let expectToBeTrue = JSObject.global.expectToBeTrue.function | ||
| else { return XCTFail("Function expectToBeTrue not found") } | ||
| // expectToBeTrue returns a Promise, so we need to await it | ||
| guard let promiseObject = expectToBeTrue().object | ||
| else { return XCTFail("expectToBeTrue() did not return an object") } | ||
| guard let promise = JSPromise(promiseObject) | ||
| else { return XCTFail("expectToBeTrue() did not return a Promise") } | ||
| let resultValue = try await promise.value | ||
| guard let result = resultValue.boolean | ||
| else { return XCTFail("expectToBeTrue() returned nil") } | ||
| XCTAssertTrue(result) | ||
| } | ||
| func testTileOfPage() async throws { | ||
| guard let getTitle = JSObject.global.getTitle.function | ||
| else { return XCTFail("Function getTitle not found") } | ||
| // getTitle returns a Promise, so we need to await it | ||
| guard let promiseObject = getTitle().object | ||
| else { return XCTFail("getTitle() did not return an object") } | ||
| guard let promise = JSPromise(promiseObject) | ||
| else { return XCTFail("expectToBeTrue() did not return a Promise") } | ||
| let resultValue = try await promise.value | ||
| guard let title = resultValue.string | ||
| else { return XCTFail("expectToBeTrue() returned nil") } | ||
| XCTAssertTrue(title == "") | ||
| } | ||
| } |
49 changes: 49 additions & 0 deletionsPlugins/PackageToJS/Fixtures/PlaywrightOnPageLoadTest/expose.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| /** | ||
| * Playwright exposed functions for PlaywrightOnPageLoadTest | ||
| * These functions will be exposed to the browser context and available as global functions | ||
| * in the WASM environment (accessible via JSObject.global) | ||
| * | ||
| * IMPORTANT: All exposed functions are async from the browser's perspective. | ||
| * Playwright's page.exposeFunction automatically wraps them to return Promises. | ||
| * Therefore, you must use JSPromise to await them in Swift. | ||
| */ | ||
| /** | ||
| * Export a function that receives the Playwright Page object and returns the exposed functions. | ||
| * This allows your functions to interact with the page (click, query DOM, etc.) | ||
| * | ||
| * @param {import('playwright').Page} page - The Playwright Page object | ||
| * @returns {Object} An object mapping function names to async functions | ||
| */ | ||
| export async function exposedFunctions(page) { | ||
| return { | ||
| expectToBeTrue: async () => { | ||
| return true; | ||
| }, | ||
| getTitle: async () => { | ||
| return await page.title(); | ||
| }, | ||
| // clickButton: async (selector) => { | ||
| // await page.click(selector); | ||
| // return true; | ||
| // }, | ||
| // screenshot: async () => { | ||
| // const buffer = await page.screenshot(); | ||
| // return buffer.toString('base64'); | ||
| // } | ||
| }; | ||
| } | ||
| /** | ||
| * Alternative: Export a static object if you don't need page access | ||
| * (Note: This approach doesn't have access to the page object) | ||
| */ | ||
| // export const exposedFunctions = { | ||
| // expectToBeTrue: async () => { | ||
| // return true; | ||
| // }, | ||
| // addNumbers: async (a, b) => a + b, | ||
| // }; |
10 changes: 10 additions & 0 deletionsPlugins/PackageToJS/Sources/PackageToJS.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
3 changes: 3 additions & 0 deletionsPlugins/PackageToJS/Sources/PackageToJSPlugin.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.