Thanks to visit codestin.com
Credit goes to github.com

Skip to content

API Test Guide

bnham edited this page May 6, 2026 · 4 revisions

Guide to Writing API Tests

Swift Testing

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!"))
}

Writing a new test

  1. Add a new ABCTests.swift file to the relevant directory in TestWebKitAPI, such as in Tests/WebKit/WebPage
  2. Set the file's Target Membership to be TestWebKitAPI and TestWebKitAPIBundle.
  3. 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.

Running a test

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" --pretty

For instance:

$ run-api-tests 'WebPageTests/javaScriptEvaluation()'

or:

$ TestWebKitAPI --filter 'WebPageTests/javaScriptEvaluation()'

How do I...?

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
}

Google Tests

Prefer writing new API tests using Swift Testing.

Clone this wiki locally