Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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
kateinoigakukun merged 4 commits intomainfromplaywright-onPageLoad
Nov 8, 2025
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletionsPlugins/PackageToJS/Fixtures/PlaywrightOnPageLoadTest/README.md
View file
Open in desktop
Original file line numberDiff line numberDiff 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
View file
Open in desktop
Original file line numberDiff line numberDiff 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"
)
]
)
View file
Open in desktop
Original file line numberDiff line numberDiff 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 == "")
}
View file
Open in desktop
Original file line numberDiff line numberDiff 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"
)
]
)
View file
Open in desktop
Original file line numberDiff line numberDiff 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 == "")
}
}
View file
Open in desktop
Original file line numberDiff line numberDiff 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
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -58,6 +58,8 @@ struct PackageToJS {
var environment: String?
/// Whether to run tests in the browser with inspector enabled
var inspect: Bool
/// The script defining Playwright exposed functions
var playwrightExpose: String?
/// The extra arguments to pass to node
var extraNodeArguments: [String]
/// The options for packaging
Expand DownExpand Up@@ -89,6 +91,14 @@ struct PackageToJS {
testJsArguments.append("--prelude")
testJsArguments.append(preludeURL.path)
}
if let playwrightExpose = testOptions.playwrightExpose {
let playwrightExposeURL = URL(
fileURLWithPath: playwrightExpose,
relativeTo: URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
)
testJsArguments.append("--playwright-expose")
testJsArguments.append(playwrightExposeURL.path)
}
if let environment = testOptions.environment {
testJsArguments.append("--environment")
testJsArguments.append(environment)
Expand Down
3 changes: 3 additions & 0 deletionsPlugins/PackageToJS/Sources/PackageToJSPlugin.swift
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -551,6 +551,7 @@ extension PackageToJS.TestOptions {
let prelude = extractor.extractOption(named: "prelude").last
let environment = extractor.extractOption(named: "environment").last
let inspect = extractor.extractFlag(named: "inspect")
let playwrightExpose = extractor.extractOption(named: "playwright-expose").last
let extraNodeArguments = extractor.extractSingleDashOption(named: "Xnode")
let packageOptions = try PackageToJS.PackageOptions.parse(from: &extractor)
var options = PackageToJS.TestOptions(
Expand All@@ -560,6 +561,7 @@ extension PackageToJS.TestOptions {
prelude: prelude,
environment: environment,
inspect: inspect != 0,
playwrightExpose: playwrightExpose,
extraNodeArguments: extraNodeArguments,
packageOptions: packageOptions
)
Expand All@@ -582,6 +584,7 @@ extension PackageToJS.TestOptions {
--prelude <path> Path to the prelude script
--environment <name> The environment to use for the tests (values: node, browser; default: node)
--inspect Whether to run tests in the browser with inspector enabled
--playwright-expose <path> Path to script defining Playwright exposed functions
-Xnode <args> Extra arguments to pass to Node.js
\(PackageToJS.PackageOptions.optionsHelp())

Expand Down
Loading

[8]ページ先頭

©2009-2025 Movatter.jp