Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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 deletions Plugins/PackageToJS/Fixtures/PlaywrightOnPageLoadTest/README.md
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
*/
export async function exposedFunctions(page) {
return {
expectToBeTrue: async () => {
return true;
},

// Use the page object to interact with the browser
getTitle: async () => {
return await page.title();
},

clickButton: async (selector) => {
await page.click(selector);
return true;
},

evaluate: async (script) => {
return await page.evaluate(script);
},

screenshot: async () => {
const buffer = await page.screenshot();
return buffer.toString('base64');
}
};
}
```

#### Option 2: Static Object (Simple Cases)

For simple functions that don't need page access:

```javascript
export const exposedFunctions = {
expectToBeTrue: async () => {
return true;
},

addNumbers: async (a, b) => {
return a + b;
}
};
```

### Use the functions in Swift tests

```swift
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") }

// Functions exposed via Playwright return Promises
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)
}
}
```

### Run tests with the expose script

```bash
swift package js test --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 js test --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
export async function exposedFunctions(page) {
// Perform async setup
const config = await loadConfiguration();

// Navigate to a specific page if needed
await page.goto('http://example.com');

return {
expectToBeTrue: async () => true,

getConfig: async () => config,

// Function that uses both page and initialization data
checkElement: async (selector) => {
const element = await page.$(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
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"
)
]
)
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 == "")
}
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"
)
]
)
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 deletions Plugins/PackageToJS/Fixtures/PlaywrightOnPageLoadTest/expose.js
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 deletions Plugins/PackageToJS/Sources/PackageToJS.swift
Original file line number Diff line number Diff 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 Down Expand 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 deletions Plugins/PackageToJS/Sources/PackageToJSPlugin.swift
Original file line number Diff line number Diff 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