-
Notifications
You must be signed in to change notification settings - Fork 2k
API Test Guide
The Swift Testing framework is the modern way to write unit tests. It is currently compatible with all Cocoa platforms in WebKit. See the Swift Testing API for more documentation.
A simple Swift test can look something like this:
@Test
func videoCommenting() async throws {
let video = try #require(await videoLibrary.video(named: "A Beach"))
#expect(video.comments.contains("So picturesque!"))
}- Add a new
ABCTests.swiftfile to the relevant directory in TestWebKitAPI, such as inTests/WebKit/WebPage - Set the file's Target Membership to be
TestWebKitAPIandTestWebKitAPIBundle. - Write the test (usually, within an existing or new suite)!
Generally, when writing a Swift Testing test, it is best practice to test the WebPage API instead of WKWebView due to natural async/await support
and more ergonomic use.
Swift Testing tests can be run natively inside Xcode, directly from CLI, or by using the run-api-tests script.
Xcode: Run a test or suite by clicking the test diamond button next to the test or suite name, or run them by using the Xcode Test Navigator UI.
CLI: The test binary can be run directly via
<path-to-TestWebKitAPI> --filter "SuiteNameOrTestName" --prettyFor instance:
$ run-api-tests 'WebPageTests/javaScriptEvaluation()'
or:
$ TestWebKitAPI --filter 'WebPageTests/javaScriptEvaluation()'
Load and wait for some HTML content to load:
let webPage = WebPage()
let html = """
<body>
<div>Hello, world!</div>
</body>
"""
try await webPage.load(html: html).wait()Evaluate JavaScript:
For simple, one-off evaluations, use the WebPage.callJavaScript API:
try await page.callJavaScript("document.body.focus()")For common, re-usable expressions, add a new expression type to JavaScriptMessages.swift:
extension JavaScriptMessages {
public struct Add: WebPage.JavaScriptExpression {
public typealias Output = Int
public let a: Int
public let b: Int
public static var expression: String {
"""
return a + b;
"""
}
public func encoded() -> [String : Any?] {
[
"a": a,
"b": b,
]
}
}
}and then use it:
let result = try await page.callJavaScript(JavaScriptMessages.Add(a: 1, b: 2)) // result is typed as an `Int`!Create an HTTP Server:
Use the new HTTPServer type designed for Swift:
let server = HTTPServer(protocol: .httpsProxy) {
Route("/example") {
"<script>w = window.open('https://webkit.org/webkit/success')</script>"
}
Route("/webkit/success") {
"Loaded!"
}
}
let page = WebPage()
let result = try await server.run {
let destination = address.appendingPathComponent("example")
try await page.load(destination).wait()
return page.url
}Prefer writing new API tests using Swift Testing.